Page 75 - Beginning PHP 5.3
P. 75
Chapter 3: PHP Language Basics
To pass a variable to a function, place the variable between parentheses after the function name — for
example, gettype( $x ) . If you need to pass more than one variable, separate them by commas. (You
learn more about how functions work, and how to use them, in Chapter 7 .)
The following example shows gettype() in action. A variable is declared, and its type is tested with
gettype() . Then, four different types of data are assigned to the variable, and the variable ’ s type is
retested with gettype() each time:
$test_var; // Declares the $test_var variable without initializing it
echo gettype( $test_var ) . “ < br / > ”; // Displays “NULL”
$test_var = 15;
echo gettype( $test_var ) . “ < br / > ”; // Displays “integer”
$test_var = 8.23;
echo gettype( $test_var ) . “ < br / > ”; // Displays “double”
$test_var = “Hello, world!”;
echo gettype( $test_var ) . “ < br / > ”; // Displays “string”
The $test_var variable initially has a type of null , because it has been created but not initialized
(assigned a value). After setting $test_var ’ s value to 15 , its type changes to integer . Setting
$test_var to 8.23 changes its type to double (which in PHP means the same as float , because all
PHP floating - point numbers are double - precision). Finally, setting $test_var to “ Hello, world! ”
alters its type to string .
In PHP, a floating - point value is simply a value with a decimal point. So if 15.0 was used instead of 15 in
the preceding example, $test_var would become a double, rather than an integer.
You can also test a variable for a specific data type using PHP ’ s type testing functions:
Function Description
is_int( value ) Returns true if value is an integer
is_float( value ) Returns true if value is a float
is_string( value ) Returns true if value is a string
is_bool( value ) Returns true if value is a Boolean
is_array( value ) Returns true if value is an array
is_object( value ) Returns true if value is an object
is_resource( value ) Returns true if value is a resource
is_null( value ) Returns true if value is null
37
c03.indd 37 9/21/09 8:51:22 AM
9/21/09 8:51:22 AM
c03.indd 37