Data Types

PHP has many of the data types that a language such as C/C++ has. It uses the three basic types: integer, double, and string. PHP also uses constants, arrays, and objects. The unique part of PHP is that you do not explicitly declare the type for the variable in PHP. The reason for this is that PHP converts the variables on the fly to the appropriate type. This is called type juggling. Here is an example of creating variables using the three basic types:

$var1 = 1;       // integer
$var2 = 2.0;    // double
$var3 = “21“; // string

NOTE

All variables start with a $, and must then begin with a non-numeric character. It is good practice to declare all of your variables before using them; although this is not required, it makes that code a bit clearer for anyone who is reading it.

You might have noticed that the Boolean type was not mentioned. That is because PHP does not support it. Instead, PHP evaluates true and false like C/C++ does. Any integer that equals 0 will evaluate to false and anything that is non-zero will evaluate to true. With strings, any string that is blank (““) will evaluate to false, and any string with a character in it will evaluate to true.

Variables in PHP are also case sensitive. That means that $someVar is not the same as $SomeVar.However, built-in functions and structures are not case sensitive. So echo is the same as ECHO.

To further clarify the concept of type juggling, check out the following examples:

 
$somevar  = 1;                        // This is currently set to an integer.
$somevar = 2.67;                      // It is now set to a double.
$somevar = “123A String“;             // It is now set to a string.
$x = 1;                               // This is an integer.
                                      // This is still an integer. After the addition the
                                         value is now 126.

$x = 3 + $somevar;

See how that works? It can come in handy in some cases because it cuts back on the number of variables you will need. In the same respect it can get pretty crazy if you’re trying to debug some code and it is juggling types on you.

When PHP is type juggling strings, it follows a few basic rules. If the string begins with a valid integer, the string will evaluate to that value. If the string includes an integer and it is not at the beginning, the string will evaluate to 0. A string will be type cast as a double if and only if the value of the string is the double. So the string “1.10”will evaluate to a double with the value 1.10.But a string with the value 88.5 percent will evaluate as an integer with a value of 88.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset