Page 76 - Beginning PHP 5.3
P. 76
Part II: Learning the Language
(You learn how to test things, and alter the flow of your script, in Chapter 4 .)
It ’ s best to use gettype() only when you want to debug a script to pinpoint a bug that might be related
to data types. Use the specific type testing functions if you simply want to ensure a variable is of the
right type; for example, it ’ s a good idea to test that an argument passed to a function is of the expected
type before you use it within the function. This helps to make your code more robust and secure. (You
learn all about functions and arguments in Chapter 7 .)
Changing a Variable ’ s Data Type
Earlier, you learned how to change a variable ’ s type by assigning different values to the variable.
However, you can use PHP ’ s settype() function to change the type of a variable while preserving the
variable ’ s value as much as possible. To use settype() , pass in the name of the variable you want to
alter, followed by the type to change the variable to (in quotation marks).
Here ’ s some example code that converts a variable to various different types using settype() :
$test_var = 8.23;
echo $test_var . “ < br / > ”; // Displays “8.23”
settype( $test_var, “string” );
echo $test_var . “ < br / > ”; // Displays “8.23”
settype( $test_var, “integer” );
echo $test_var . “ < br / > ”; // Displays “8”
settype( $test_var, “float” );
echo $test_var . “ < br / > ”; // Displays “8”
settype( $test_var, “boolean” );
echo $test_var . “ < br / > ”; // Displays “1”
To start with, the $test_var variable contains 8.23 , a floating - point value. Next, $test_var is converted
to a string, which means that the number 8.23 is now stored using the characters 8 , . (period), 2 , and 3 .
After converting $test_var to an integer type, it contains the value 8 ; in other words, the fractional part
of the number has been lost permanently. You can see this in the next two lines, which convert $test_var
back to a float and display its contents. Even though $test_var is a floating - point variable again, it now
contains the whole number 8 . Finally, after converting $test_var to a Boolean, it contains the value true
(which PHP displays as 1 ). This is because PHP converts a non - zero number to the Boolean value true .
Find out more about what PHP considers to be true and false in the “ Logical Operators ” section
later in this chapter.
Changing Type by Casting
You can also cause a variable ’ s value to be treated as a specific type using a technique known as type
casting . This involves placing the name of the desired data type in parentheses before the variable ’ s
name. Note that the variable itself remains unaffected; this is in contrast to settype() , which changes
the variable ’ s type.
38
9/21/09 8:51:22 AM
c03.indd 38 9/21/09 8:51:22 AM
c03.indd 38