Automatic type conversion
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 are demonstrated 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 = 40 + "2 blind mice"; // $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
|