|[ Team LiB ]|
Different types of data take up different amounts of memory and can be treated differently when they are manipulated in a script. Some programming languages therefore demand that the programmer declare in advance which type of data a variable will contain. By contrast, PHP is loosely typed, which means it calculates data types as data is assigned to each variable. This is a mixed blessing. On the one hand, it means that variables can be used flexibly, holding a string at one point and an integer at another. On the other hand, this can lead to problems in larger scripts if you expect a variable to hold one data type when, in fact, it holds something completely different. You might have created code designed to work with an array variable, for example. If the variable in question contains a number value instead, errors might occur when the code attempts to perform array-specific operations on the variable.
Table 4.1 shows the six standard data types available in PHP.
PHP also provides two special data types, which are listed in Table 4.2.
Resource types are often returned by functions that deal with external applications or files. You will see examples of resource types throughout the book. The type NULL is reserved for variables that have not been initialized (that is, they have not yet had a value assigned to them).
You can use PHP's built-in function gettype () to acquire the type of any variable. If you place a variable between the parentheses of the function call, gettype() returns a string representing the relevant type. Listing 4.1 assigns five different data types to a single variable, testing it with gettype() each time.
1: <!DOCTYPE html PUBLIC 2: "-//W3C//DTD XHTML 1.0 Strict//EN" 3: "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> 4: <html> 5: <head> 6: <title>Listing 4.1 Testing the type of a variable</title> 7: </head> 8: <body> 9: <div> 10: <?php 11: $testing; // declare without assigning 12: print gettype( $testing ); // NULL 13: print "<br />"; 14: $testing = 5; 15: print gettype( $testing ); // integer 16: print "<br />"; 17: $testing = "five"; 18: print gettype( $testing ); // string 19: print "<br />"; 20: $testing = 5.0; 21: print gettype( $testing ); // double 22: print "<br />"; 23: $testing = true; 24: print gettype( $testing ); // boolean 25: print "<br />"; 26: ?> 27: </div> 28: </body>
This script produces the following:
NULL integer string double boolean
When we declare our $testing variable in line 11, we do not assign a value to it. So, when we first use the gettype() function to test the variable in line 12, we get the string NULL. After this, we assign values to $testing by using = before passing it to gettype(). An integer (5), assigned to the $testing variable in line 14, is a whole or real number. In simple terms, it can be said to be a number without a decimal point. A string ("five"), assigned to the $testing variable in line 17, is a collection of characters. When you work with strings in your scripts, they should always be surrounded by double quotation marks (") or single quotation marks ('). A double (5.0), assigned to the $testing variable in line 20, is a floating-point number. That is, it's a number that includes a decimal point. A boolean (true), assigned to the $testing variable in line 23, can be one of two special values: true or false.
Displaying Type Information with var_dump()
gettype() is a specialized tool. It does what it promises and returns a variable's type. var_dump() tells you a variable's type and its contents. More than that, for complex types such as arrays and objects, var_dump() provides information about all the types contained within the variable, as well as about the variable itself.
So, by altering line 11 of Listing 4.1, we can put var_dump() to the test:
$testing = 5; var_dump( $testing );
This fragment gives us the following result:
This tells us that the variable $testing contains an integer and that the value of that integer is 5. Notice that we did not need to print the result of var_dump(); this is because the function prints its findings directly to the browser or command line.
Testing for a Specific Data Type
gettype() is useful for debugging because it tells you exactly what type any variable is. Often, though, you will want to check only whether a variable contains a specific type. PHP provides a special function corresponding to each data type. These functions accept a variable or value and return a boolean. Table 4.3 lists these functions.
In Hour 5, "Going with the Flow," we examine the if statement, which enables you to alter the behavior of a script according to the results of a test. These type testing functions are frequently used in conjunction with if statements to enforce the type of a variable passed to a function or object method.
Changing Type with settype()
PHP provides the function settype() to change the type of a variable. To use settype(), you must place the variable to change (and the type to change it to) between the parentheses and separate them by commas. Listing 4.2 converts the value 3.14 (a double) to the four types we are covering in this hour.
1: <!DOCTYPE html PUBLIC 2: "-//W3C//DTD XHTML 1.0 Strict//EN" 3: "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> 4: <html> 5: <head> 6: <title> Listing 4.2 Changing the Type of a Variable with settype()</title> 7: </head> 8: <body> 9: <div> 10: <?php 11: $undecided = 3.14; 12: print gettype( $undecided ); // double 13: print " -- $undecided<br />"; // 3.14 14: settype( $undecided, string ); 15: print gettype( $undecided ); // string 16: print " -- $undecided<br />"; // 3.14 17: settype( $undecided, int ); 18: print gettype( $undecided ); // integer 19: print " -- $undecided<br />"; // 3 20: settype( $undecided, double ); 21: print gettype( $undecided ); // double 22: print " -- $undecided<br />"; // 3.0 23: settype( $undecided, bool ); 24: print gettype( $undecided ); // boolean 25: print " -- $undecided<br />"; // 1 26: ?> 27: </div> 28: </body> 29: </html>
In each case, we use gettype() to confirm that the type change worked and then print the value of the variable $undecided to the browser. When we convert the string 3.14 to an integer in line 17, any information beyond the decimal point is lost forever. That's why $undecided still contains 3 after we have changed it back to a double in line 20. Finally, in line 23, we convert $undecided to a boolean.
Changing Type by Casting
The principle difference between settype() and a cast is the fact that casting produces a copy, leaving the original variable untouched. Listing 4.3 illustrates this.
1: <!DOCTYPE html PUBLIC 2: "-//W3C//DTD XHTML 1.0 Strict//EN" 3: "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> 4: <html> 5: <head> 6: <title> Listing 4.3 Casting a Variable</title> 7: </head> 8: <body> 9: <div> 10: <?php 11: $undecided = 3.14; 12: $holder = ( double ) $undecided; 13: print gettype( $holder ) ; // double 14: print " -- $holder<br />"; // 3.14 15: $holder = ( string ) $undecided; 16: print gettype( $holder ); // string 17: print " -- $holder<br />"; // 3.14 18: $holder = ( integer ) $undecided; 19: print gettype( $holder ); // integer 20: print " -- $holder<br />"; // 3 21: $holder = ( double ) $undecided; 22: print gettype( $holder ); // double 23: print " -- $holder<br />"; // 3.14 24: $holder = ( boolean ) $undecided; 25: print gettype( $holder ); // boolean 26: print " -- $holder<br />"; // 1 27: ?> 28: </div> 29: </body> 30: </html>
We never actually change the type of $undecided, which remains a double throughout. We illustrate this on line 25 by using the gettype() function to output the type of $undecided.
In fact, by casting $undecided, we create a copy that is then converted to the type we specify. This new value is then stored in the variable $holder, first in line 12 and then also in lines 15, 18, 21, and 24. Because we are working with a copy of $undecided, we never discard any information from it as we did in lines 17 and 23 of Listing 4.2.
Now that we can change the contents of a variable from one type to another, either using settype() or a cast, we should consider why this might be useful. It is certainly not a procedure you will use often because PHP automatically casts for you when the context requires. However, an automatic cast is temporary, and you might want to make a variable persistently hold a particular data type.
Numbers typed in to an HTML form by a user are made available to your script as a string. If you try to add two strings containing numbers, PHP helpfully converts the strings into numbers while the addition is taking place. So
"30cm" + "40cm"
produces the integer 70. In casting the strings, PHP ignores the non-numeric characters. However, you might want to clean up your user input yourself. Imagine that a user has been asked to submit a number. We can simulate this by declaring a variable and assigning to it, like so:
$test = "30cm";
$test = (integer)$test; print "Your imaginary box has a width of $test centimeters";
More Ways of Changing Type
You have already seen two ways of converting data types: You can cast a value or use the settype() function. In addition to these techniques, PHP provides functions to convert values into integers, doubles, and strings. These functions accept values of any type apart from array or object and return a converted value. Table 4.4 lists these functions.
Why Test Type?
Why might it be useful to know the type of a variable? Many circumstances occur in programming in which data is passed to you from another source. In Hour 6, for example, you learn how to create functions in your scripts. Functions can accept information from calling code in the form of arguments. For the function to work with the data it is given, you often need to first check that it has been given values of the correct data type. A function that is expecting a resource, for example, will not work well when passed a string.
|[ Team LiB ]|