Data Types

Different types of data take up different amounts of memory and may 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, meaning that it will calculate 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. For example, suppose you have created code that is designed to work with an array variable. If the variable in question instead contains a number value, 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.

Table 4.1. Standard Data Types

Type

Example

Description

Integer

5

A whole number

Double

3.234

A floating-point number

String

"hello"

A collection of characters

Boolean

true

One of the special values true or false

Object

An instance of a class

Array

An ordered set of keys and values

PHP also provides two special data types, listed in Table 4.2.

Table 4.2. Special Data Types

Type

Description

Resource

Reference to a third-party resource (a database, for example)

NULL

An uninitialized variable

Resource types are often returned by functions that deal with external applications or files. The type NULL is reserved for variables that have not been initialized (that is, variables that have not yet had a value assigned to them).

You can use PHP's built-in function gettype() to test 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.

graphics/book.gif

You can read more about calling functions in Hour 6, "Working with Functions,"


Listing 4.1 Testing the Type of a Variable
   1: <html>   2: <head>   3: <title>Listing 4.1 Testing the type of a variable</title>   4: </head>   5: <body>   6: <?php   7: $testing; // declare without assigning   8: print gettype( $testing ); // null   9: print "<br>";  10: $testing = 5;  11: print gettype( $testing ); // integer  12: print "<br>";  13: $testing = "five";  14: print gettype( $testing ); // string  15: print("<br>");  16: $testing = 5.0;  17: print gettype( $testing ); // double  18: print("<br>");  19: $testing = true;  20: print gettype( $testing ); // boolean  21: print "<br>";  22: ?>  23: </body>  24: </html> 

Put these lines into a text file called gettype.php, and place this file in your Web server document root. When you access this script through your Web browser, it produces the following:

 NULL integer string double boolean 

When we declare the $testing variable in line 7, we do not assign a value to it, so when we first use the gettype() function to test the variable in line 8, we get the string NULL. After this, we assign values to $testing by using the = sign before passing it to gettype(). An integer, assigned to the $testing variable in line 10, is a whole or real number. In simple terms, you can think of it as a number without a decimal point. A string, assigned to the $testing variable in line 13, is a collection of characters. When you work with strings in your scripts, they should always be surrounded by double or single quotation marks (" or '). A double, assigned to the $testing variable in line 16, is a floating-point number (that is, a number that includes a decimal point). A Boolean, assigned to the $testing variable in line 19, can have one of two special values, true or false.

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 with a comma. Listing 4.2 converts the value 3.14 (a double) to each of the four types that we are focusing on in this hour.

Listing 4.2 Changing the Type of a Variable with settype()
   1: <html>   2: <head>   3: <title>Listing 4.2 Changing the type of a variable with settype()</title>   4: </head>   5: <body>   6: <?php   7: $undecided = 3.14;   8: print gettype( $undecided ); // double   9: print " is $undecided<br>";  // 3.14  10: settype( $undecided, 'string' );  11: print gettype( $undecided ); // string  12: print " is $undecided<br>";  // 3.14  13: settype( $undecided, 'integer' );  14: print gettype( $undecided ); // integer  15: print " is $undecided<br>";  // 3  16: settype( $undecided, 'double' );  17: print gettype( $undecided ); // double  18: print " is $undecided<br>";  // 3.0  19: settype( $undecided, 'boolean' );  20: print gettype( $undecided ); // boolean  21: print " is $undecided<br>";  // 1  22: ?>  23: </body>  24: </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 13, any information beyond the decimal point is lost forever. That's why $undecided contains 3.0 after we change it back to a double in line 16. Finally, in line 19, we convert $undecided to a Boolean. Any number other than 0 becomes true when converted to a Boolean. When printing a Boolean in PHP, true is represented as 1 and false is represented as an empty string, so in line 21, $undecided is printed as 1.

Put these lines into a text file called settype.php, and place this file in your Web server document root. When you access this script through your Web browser, it produces the following:

 double is 3.14 string is 3.14 integer is 3 double is 3 boolean is 1 

Changing Type by Casting

By placing the name of a data type in parentheses in front of a variable, you create a copy of that variable's value converted to the data type specified.

The principal difference between a settype() and a cast is the fact that casting produces a copy, leaving the original variable untouched. Listing 4.3 illustrates this.

Listing 4.3 Casting a Variable
   1: <html>   2: <head>   3: <title>Listing 4.3 Casting a variable</title>   4: </head>   5: <body>   6: <?php   7: $undecided = 3.14;   8: $holder = ( double ) $undecided;   9: print gettype( $holder ) ; // double  10: print " is $holder<br>";   // 3.14  11: $holder = ( string ) $undecided;  12: print gettype( $holder );  // string  13: print " is $holder<br>";   // 3.14  14: $holder = ( integer ) $undecided;  15: print gettype( $holder );  // integer  16: print " is $holder<br>";   // 3  17: $holder = ( double ) $undecided;  18: print gettype( $holder );  // double  19: print " is $holder<br>";   // 3.14  20: $holder = ( boolean ) $undecided;  21: print gettype( $holder );  // boolean  22: print " is $holder<br>";   // 1  23: print "<hr>";  24: print "original variable type: ";  25: print gettype( $undecided ); // double  26: ?>  27: </body>  28: </html> 

We never actually change the type of $undecided, which remains a double throughout. This is illustrated on line 25, where we use 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 stored in the variable $holder, first in line 8, and also in lines 11, 14, 17, and 20. Because we are working with a copy of $undecided, we never discard any information from it as we did in lines 13 and 19 of Listing 4.2.

Put these lines into a text file called testcast.php, and place this file in your Web server document root. When you access this script through your Web browser, it produces the following:

 double is 3.14 string is 3.14 integer is 3 double is 3.14 boolean is 1 original variable type: double 

Now that we can change the contents of a variable from one type to another, using either settype() or a cast, we should consider why this might be useful. It is certainly not a procedure that you will use often because PHP will automatically cast for you when the context requires. However, an automatic cast is temporary, and you might wish to make a variable persistently hold a particular data type.

Numbers that a user types into an HTML form will be made available to your script as a string. If you try to add two strings containing numbers, PHP will helpfully convert the strings into numbers while the addition is taking place. So

 "30cm" + "40cm" 

will give the integer 70. In casting the strings, PHP will ignore the non-numeric characters. However, you might want to clean up the user input yourself. Imagine that the user has been asked to submit a number. We can simulate this by declaring a variable and assigning to it:

 $test = "30cm"; 

As you can see, the user has added units to the number. We can make sure that the user input is clean by casting it to an integer:

 $test = (integer)$test; print "Your imaginary box has a width of $test centimeters"; 

Why Test Type?

Why might it be useful to know the type of a variable? There are often circumstances in programming in which data is passed to you from another source. In Hour 6, for example, you will 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, it is often a good idea to first verify 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.



Sams Teach Yourself PHP, MySQL and Apache in 24 Hours
Sams Teach Yourself PHP, MySQL and Apache in 24 Hours
ISBN: 067232489X
EAN: 2147483647
Year: 2005
Pages: 263

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net