PHP is a loosely typed language, allowing variables and function parameters to be set to any type of data. Similarly, functions can return different data types in different circumstances.
In the last section, we introduced the function prototype as a way of describing the type of parameters that functions are designed to work with and the types of data that are returned. Since PHP is loosely typed, PHP can't enforce these types as strongly typed languages do. To illustrate this, the PHP library function strtoupper( ) is designed to operate on strings, but can be called with an integer parameter:
$var = 42; print strtoupper($var); // prints the string "42"
When functions are designed to work with different data types, prototypes describe parameters and return values as mixed. Other functions may not work as expected, or may not work at all, when the wrong type of data is used.
PHP provides several mechanisms to allow variables of one type to be considered as another type. Variables can be explicitly converted to another type with the following functions:
The functions convert the variable into a string, integer, or float respectively. The intval( ) function also allows an optional base that determines how the variable is interpreted.
$year = 2003; // Sets $yearString to the string value "2003" $yearString = strval($year); $var = "abc"; // sets $value to the integer 0 $value = intval($var); // sets $count to the integer value 2748 - the // integer value of "abc" as a hexadecimal number $count = intval($var, 16);
Because the string "abc" doesn't look anything like an integer, the first call to the intval( ) function sets $value to zero.
PHP also supports type conversion with type-casting operators in much the same way as C, to allow the type of an expression to be changed. When you place the type name in parentheses in front of a variable, PHP converts the value to the desired type:
// cast to an integer: the following are equivalent $int = (int) $var; $int = (integer) $var; $int = intval($var); // cast to a Boolean $bool = (bool) $var; $bool = (boolean) $var; // cast to a float $float = (float) $var; $float = floatval($var); // cast to a string $str = (string) $var; $str = strval($var); // cast to an array $arr = (array) $var; // cast to an object $obj = (object) $var;
In the previous example, type casting, and calls to the strval( ), intval( ), and floatval( ) functions don't change the value or type of the variable $var. The settype( ) function actually modifies the variable that it is called with. For example:
boolean settype(mixed variable, string type)
settype( ) explicitly sets the type of variable to type, where type is one of array, boolean, float, integer, object, or string.
// cast to an integer: the following are equivalent $var = 39; // $var is now a string settype($var, "string");
The rules for converting types are mostly common sense, but some conversions may not appear so straightforward. Table 2-1 shows how various values of $var are converted using the (int), (bool), (string), and (float) casting operators.
Value of $var |
(int) $var |
(bool) $var |
(string) $var |
(float) $var |
---|---|---|---|---|
null |
0 |
false |
"" |
0 |
true |
1 |
true |
"1" |
1 |
false |
0 |
false |
"" |
0 |
0 |
0 |
false |
"0" |
0 |
3.8 |
3 |
true |
"3.8" |
3.8 |
"0" |
0 |
false |
"0" |
0 |
"10" |
10 |
true |
"10" |
10 |
"6 feet" |
6 |
true |
"6 feet" |
6 |
"foo" |
0 |
true |
"foo" |
0 |
Automatic type conversion occurs when two differently typed variables are combined in an expression or when a variable is passed as an argument to a library function that expects a different type. When a variable of one type is used as if it were another type, PHP automatically converts the variable to a value of the required type. The same rules are used for automatic type conversion as demonstrated previously in Table 2-1.
Some simple examples show what happens when strings are added to integers and floats, and when strings and integers are concatenated:
// $var is set as an integer = 115 $var = "100" + 15; // $var is set as a float = 115.0 $var = "100" + 15.0; // $var is set as a string = "39 Steps" $var = 39 . " Steps";
Not all type conversions are so obvious and can be the cause of hard-to-find bugs:
// $var is set as an integer = 39 $var = 39 + " Steps"; // $var is an integer = 42 $var = "3 blind mice" + 39; // $var is a float, but what does it mean? $var = "test" * 4 + 3.14159;
Automatic type conversion can change the type of a variable. Consider the following example:
$var = "1"; // $var is a string == "1" $var += 2; // $var is now an integer == 3 $var /= 2; // $var is now a float == 1.5 $var *= 2; // $var is still a float == 3
|
Because PHP is flexible with types, it provides the following functions that can check a variable's type:
All the functions return a Boolean value of true or false depending on whether the type of variable matches the variable type that forms the name of the function. For example, is_float( ) evaluates to true in the following code:
$test = 13.0; // prints "Variable is a float" if (is_float($test)) print "Variable is a float";
While the PHP equals operator == tests the values of two variables, it doesn't test the variables types. Consider the comparisons of string and integer variables:
$stringVar = "10 reasons to test variable type"; $integerVar = 10; // Prints "Variables have the same value" if ($stringVar == $integerVar) print "Variables have the same value";
Because of PHP's automatic type conversion, $stringVar == $integerVar evaluates to true. PHP provides the is-identical operator === that tests not only values, but types. In the fragment below, the expression $stringVar === $integerVar evaluates to false:
$stringVar = "10 reasons to test variable type"; $integerVar = 10; // Does not print anything if ($stringVar === $integerVar) print "Variables have the same value and type";
PHP also provides the is-not-identical operator, !== , that returns true if the value or type of two expressions are different.
PHP provides the gettype( ) , print_r( ), and var_dump( ) functions, which print the type and value of an expression in a human-readable form:
These functions are useful for debugging a script, especially when dealing with arrays or objects. To test the value and type of $variable at some point in the script, the following code can be used:
$variable = "3 Blind mice" + 39; var_dump($variable);
This prints:
int(42)
While the var_dump( ) function allows multiple variables to be tested in one call, and provides information about the size of the variable contents, print_r( ) provides a more concise representation of arrays and objects, and will prove useful later when we start to use those variables.
The gettype( ) function simply returns the type name for an expression:
$variable = "3 Blind mice" + 39; // prints: "integer" print(gettype($variable));
The name that gettype( ) returns should only be used for information and not to programmatically test the type of a variable as the output is not guaranteed to remain stable with future PHP releases. To programmatically test a variable type, you should use the is_int( ), is_float( ), is_bool( ), is_string( ), is_array( ), or is_object( ) functions described earlier.
The gettype( ), print_r( ), and var_dump( ) functions can be used on variables and expressions of any type, and we use them throughout the book to help illustrate the results of our examples.
During the running of a PHP script, a variable may be in an unset state or may not yet be defined. PHP provides the isset( ) function and the empty( ) language construct to test the state of variables:
isset( ) tests if a variable has been set with a non-null value, while empty( ) tests if a variable is equal to false. The two are illustrated by the following code:
$var = 0; // prints: "Variable is Set" if (isset($var)) print "Variable is Set"; // prints: "Variable is Empty" if (empty($var)) print "Variable is Empty"; $var = "test"; // prints: "Variable is Set" if (isset($var)) print "Variable is Set"; // Doesn't print if (empty($var)) print "Variable is Empty";
A variable can be explicitly destroyed using unset( ) :
After the call to unset in the following example, $var is no longer defined:
$var = "foo"; // Later in the script unset($var); // Does not print if (isset($var)) print "Variable is Set";
Table 2-2 show the return values for isset($var) and empty($var)when the variable $var is tested. Some of the results may be unexpected: when $var is set to "0," empty( ) returns true.
State of the variable $var |
isset($var) |
empty($var) |
---|---|---|
unset $var; |
false |
true |
$var = null; |
false |
true |
$var = 0; |
true |
true |
$var = true; |
true |
false |
$var = false; |
true |
true |
$var = "0"; |
true |
true |
$var = ""; |
true |
true |
$var = "foo"; |
true |
false |
$var = array( ); |
true |
true |
A variable is always set when it is assigned a value?with the exception of a null assignment?and isset( ) returns true. The empty( ) function tests the Boolean value of the variable and returns true if the variable is false. The statement
$result = empty($var);
is equivalent to
$result = not (boolean) $var;
However, PHP issues a warning when a cast operator is used on an unset variable, whereas empty( ) doesn't.