Wednesday, September 29, 2010

Data Types in php

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. PHP4 is loosely typed, which means 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 confusion in larger scripts if
you expect a variable to hold one data type when in fact it holds something
completely different.

Type                        Example                    Description
Integer                        5                          A whole number
Double                    3.234                     A floating-point
number
String                     "hello"                  A collection ofcharacters
Boolean                   true                          One of the special values true or false
Object                 "Objects"
Array See                "Arrays"

You can use PHP4'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.4 assigns four different data types to
a single variable, testing it with gettype() each time.
Note You can read more about calling functions in Hour 6, "Functions."

1: <html>
2: <head>
3: <title>Listing 4.3 Testing the type of a variable</title>
4: </head>
5: <body>
6: <?php
7: $testing = 5;
8: print gettype( $testing ); // integer
9: print "<br>";
10: $testing = "five";
11: print gettype( $testing ); // string
12: print("<br>");
13: $testing = 5.0;
14: print gettype( $testing ); // double
15: print("<br>");
16: $testing = true;
17: print gettype( $testing ); // boolean
18: print "<br>";
19: ?>
20: </body>
21: </html>
This script produces the following:
integer
string
double
boolean
An integer is a whole or real number. In simple terms, it can be said to be a number
without a decimal point. A string is a collection of characters. When you work with
strings in your scripts, they should always be surrounded by double (") or single (')
quotation marks. A double is a floating-point number. That is, a number that
includes a decimal point. A boolean can be one of two special values, true or false.
Note Prior to PHP4, there was no boolean type. Although true was used, it
actually resolved to the integer 1.

No comments:

Post a Comment