A data type identifies the characteristics that the assigned data will be interpreted by when interacting with the PHP programming language. When a value is assigned a specific data type, the PHP interpreter will work with the data based on the expected type of data it is. For example, 27654 could be considered a numeric data type or it could be considered a string data type, such as in the zip code for a customer. Even though you could perform mathematical equations on the zip code, it would make no sense to do so. Thus,zip codes, even though they look like they would be numeric numbers should be identified as a string data type to eliminate problems such as zip codes that start with zero (ex. 08102). Assigning the correct data type to the expected value is an important part of working with PHP. There are three categories of data types in PHP: Scalar, Compound and Special.
PHP supports eight primitive types.
Four scalar types:
- boolean
- integer
- float (floating-point number, aka double)
- string
Two compound types:
- array
- object
And finally two special types:
- resource
- NULL
<?php
$a_bool = TRUE; // a boolean$a_str = "foo"; // a string$a_str2 = 'foo'; // a string$an_int = 12; // an integerecho gettype($a_bool); // prints out: booleanecho gettype($a_str); // prints out: string
// If this is an integer, increment it by fourif (is_int($an_int)) {
$an_int += 4;
}// If $a_bool is a string, print it out
// (does not print out anything)if (is_string($a_bool)) {
echo "String: $a_bool";
}?>
Scalar types
Booleans
This is the simplest type. A boolean expresses a truth value. It can be either TRUE or FALSE.
Syntax
To specify a boolean literal, use the keywords TRUE or FALSE. Both are case-insensitive.
<?php
$foo = True; // assign the value TRUE to $foo?>
$foo = True; // assign the value TRUE to $foo?>
Integers
An integer is a number of the set ℤ = {..., -2, -1, 0, 1, 2, ...}.
Syntax
Integers can be specified in decimal (base 10), hexadecimal (base 16), octal (base 8) or binary (base 2) notation, optionally preceded by a sign (- or +).
Binary integer literals are available since PHP 5.4.0.
To use octal notation, precede the number with a 0 (zero). To use hexadecimal notation precede the number with 0x. To use binary notation precede the number with 0b.
<?php
$a = 1234; // decimal number$a = -123; // a negative number$a = 0123; // octal number (equivalent to 83 decimal)$a = 0x1A; // hexadecimal number (equivalent to 26 decimal)?>
$a = 1234; // decimal number$a = -123; // a negative number$a = 0123; // octal number (equivalent to 83 decimal)$a = 0x1A; // hexadecimal number (equivalent to 26 decimal)?>
The maximum number that can be assigned to an integer is based on the system. 32 bit systems have a maximum signed integer range of -2147483648 to 2147483647. The maximum signed integer value for 64 bit systems is 9223372036854775807.Any value that exceeds the maximum integer size will be assigned the float data type
Float
Floating point numbers (also known as "floats", "doubles", or "real numbers") can be specified using any of the following syntaxes:
<?php
$a = 1.234; $b = 1.2e3; $c = 7E-10;?>
$a = 1.234; $b = 1.2e3; $c = 7E-10;?>
The size of a floating point number is dependent by the system being used. In addition, floating point numbers are not as accurate as integer numbers when it comes to precision. Even simple numbers like 0.2 and 0.17 can not be converted into their binary equivalents without a loss of precision. With that said, floating point numbers should never be used in comparison operations
without building in logic such as rounding numbers prior to the comparison operation or using a tolerance value that would be an acceptable difference between the compared values for comparison operations.
Strings
A string data type is a series of characters that are associated with each other in a defined order. There is no limit to the length of a string data value. The following represent some of the values that can be assigned to a string data type:
<?phpecho 'this is a simple string';
echo 'You can also have embedded newlines in
strings this way as it is
okay to do';// Outputs: Arnold once said: "I'll be back"echo 'Arnold once said: "I\'ll be back"';// Outputs: You deleted C:\*.*?echo 'You deleted C:\\*.*?';// Outputs: You deleted C:\*.*?echo 'You deleted C:\*.*?';// Outputs: This will not expand: \n a newlineecho 'This will not expand: \n a newline';// Outputs: Variables do not $expand $eitherecho 'Variables do not $expand $either';?>
echo 'You can also have embedded newlines in
strings this way as it is
okay to do';// Outputs: Arnold once said: "I'll be back"echo 'Arnold once said: "I\'ll be back"';// Outputs: You deleted C:\*.*?echo 'You deleted C:\\*.*?';// Outputs: You deleted C:\*.*?echo 'You deleted C:\*.*?';// Outputs: This will not expand: \n a newlineecho 'This will not expand: \n a newline';// Outputs: Variables do not $expand $eitherecho 'Variables do not $expand $either';?>
The characters that can be used in PHP string data types are limited to the ISO 8859-1 or Latin-1 character set. This character set allows for 256 (the size of a byte) different possible characters (191 of them that are actually printable); however, there is support in PHP to encode strings to the UTF-8 standard (UTF-8 is a standard mechanism used by Unicode for encoding wide character values into a byte stream).
Compound types:
A compound data type allows for multiple values to be associated with a single entity. The primary purpose of a compound data type is to act as containers for other kinds of data. In PHP, there are two types of data types that fall under into this category.
Arrays
An array in PHP is actually an ordered map. A map is a type that associates values to keys. This type is optimized for several different uses; it can be treated as an array, list (vector), hash table (an implementation of a map), dictionary, collection, stack, queue, and probably more. As array values can be other arrays, trees and multidimensional arrays are also possible.
Explanation of those data structures is beyond the scope of this manual, but at least one example is provided for each of them. For more information, look towards the considerable literature that exists about this broad topic.
<?php
$Country[0] = "Australia"; // Australia is the first(0) value
$Country[1] = "Russia"; // Russia is the second(1) value
$Country[2] = "Germany"; // Germany is the third(2) value
$Country[3] = "France"; // France is the fourth(3) value
// The following will display: Let's go to Germany!
print "Let's go to $Country[2]!";
?>
The above example could be written less explicitly:
<?php
$Country = array("Australia", "Russia", "Germany", "France");
print "Let's go to $Country[2]!";
?>
Rather than using numeric identifiers, array identifiers can be more meaningful when created as in
the following examples:
<?php
$Capital["Australia"] = "Canberra";
$Capital["Russia"] = "Moscow";
$Capital["Germany"] = "Berlin";
$Capital["France"] = "Paris";
print "The capital of Russia is ".$Capital["Russia"]."!";
?>
<?php
$Capital = array(
"Australia" => "Canberra",
"Russia" => "Moscow",
"Germany" => "Berlin",
"France" => "Paris");
print "The capital of Russia is ".$Capital["Russia"]."!";
?>
Objects
The data type referred to as an object is the key to the object-oriented programming paradigm. The object, can be thought of as a "black box" in which information is sent into it, processed and a result is sent out. The developer has no need to know anything about the internal workings of the code thus giving power to the idea of creating and using objects of already-existing code. Up to this point in the discussion of data types, there has been no need to explicitly declare a data type. PHP determines the data type based on the value that is being stored. However, objects must be explicitly declared. This declaration, which includes the object's characteristics and behavior, takes place within a class. The following is an example of an object declaration:
<?php
class respect {
private $name;
function setRespect($name) {
$this->name = 'Mr./Ms. '.$name;
print $this->name;
}
}
$boss = new respect;
$boss->setRespect("Jane Riker");
?>
In this simple object example, the result of all this coding is a proper title being placed in front of the boss' name. However, this object could be reused over and over again throughout the remained of the application:
<?php
$assistant = new respect;
$assistant->setRespect("Wes Picard");
?>
Special types:
Resources
A resource is a special variable, holding a reference to an external resource. Resources are created and used by special functions. See the appendix for a listing of all these functions and the corresponding resource types.
Converting to resource
As resource variables hold special handlers to opened files, database connections, image canvas areas and the like, converting to a resource makes no sense.
Freeing resources
Thanks to the reference-counting system introduced with PHP 4's Zend Engine, a resource with no more references to it is detected automatically, and it is freed by the garbage collector. For this reason, it is rarely necessary to free the memory manually.
One of the benefits of using PHP is its ability to interact with some external data
source: databases, files, network streams, etc. To utilize these external data sources, PHP must create handles that are named when a successful connection is initiated. These handles continue to be the main point of reference for any communication that takes place. When the communication process is completed, the handle is destroyed and the connection is terminated. These handles fall under the resource data type.
<?php
$dbLink = mysql_connect ("localhost","root","training") or
die("Could not connect to MySQL server");
$query = "SHOW TABLES FROM INFORMATION SCHEMA";
$result = mysql_query($query);
While ($row = mysql_fetch_array($result)) {
print row[0]."<br>";
}
mysql_close();
?>
In the example above, the $dbLink variable is assigned a resource data type based on the action that is taking place (connecting to the local MySQL database server). If $dbLink was referenced directly, a reference to a resource id would be returned
NULL
The special NULL value represents a variable with no value. NULL is the only possible value of type NULL.
A variable is considered to be null if:
- it has been assigned the constant NULL.
- it has not been set to any value yet.
- it has been unset().<?php$SSAN = '112-34-5677';unset($SSAN);?>
Syntax
There is only one value of type null, and that is the case-insensitive keyword NULL.
<?php
$var = NULL; ?>
Comments
Post a Comment