Wednesday, 5 December 2012

PHP OPERATORS

OPERATORS
PHP contains three types of operators: unary operators, binary operators, and
one ternary operator.
Binary operatorsare used on two operands:
2 + 3
14 * 3.1415
$i – 1
These examples are also simple examples of expressions.
PHP can only perform binary operations on two operands that have the
same type. However, if the two operands have different types, PHP automati-cally converts one of them to the other’s type, according to the following rules
(unless stated differently, such as in the concatenation operator).
Booleans, nulls, and resources behave like integers, and they convert in
the following manner:
☞Boolean: False = 0, True= 1
☞Null = 0
☞Resource = The resource’s # (id)
2.6.1 Binary Operators
2.6.1.1 Numeric Operators All the binary operators (except for the concate-
nation operator) work only on numeric operands. If one or both of the oper-
ands are strings, Booleans, nulls, or resources, they are automatically
converted to their numeric equivalents before the calculation is performed
(according to the previous table). 2.6.1.2 Concatenation Operator (.) The concatenation operatorconcate-
nates two strings. This operator works only on strings; thus, any non-string
operand is first converted to one.
The following example would print out "The year is 2000":
$year = 2000;
print "The year is " . $year;
The integer $yearis internally converted to the string "2000"before it is
concatenated with the string’s prefix, "The year is".
2.6.2 Assignment Operators
Assignment operatorsenable you to write a value to a variable. The first
operand (the one on the left of the assignment operator or l value) must be a
variable. The value of an assignment is the final value assigned to the vari-
able; for example, the expression $var = 5has the value 5(and assigns 5to
$var).In addition to the regular assignment operator =, several other assign-ment operators are composites of an operator followed by an equal sign. These
composite operators apply the operator taking the variable on the left as the
first operand and the value on the right (the r value) as the second operand,
and assign the result of the operation to the variable on the left.
For example:
$counter += 2; // This is identical to $counter = $counter + 2;
$offset *= $counter;// This is identical to $offset = $offset *
➥$counter;
The following list show the valid composite assignment operators:
+=, -=, *=, /=, %=, ^=, .=, &=, |=, <<=, >>=
2.6.2.1 By-Reference Assignment Operator PHP enables you to create vari-ables as aliases for other variables. You can achieve this by using the by-reference
assignment operator =&. After a variable aliases another variable, changes to
either one of them affects the other.
For example:
$name = "Judy";
$name_alias =& $name;
$name_alias = "Jonathan";
print $name;
The result of this example is
Jonathan
When returning a variable by-reference from a function (covered later in
this book), you also need to use the assign by-reference operator to assign the
returned variable to a variable:
$retval =& func_that_returns_by_reference();
2.6.3 Comparison Operators
Comparison operatorsenable you to determine the relationship between
two operands.
When both operands are strings, the comparison is performed lexico-graphically. The comparison results in a Boolean value.
For the following comparison operators, automatic type conversions are
performed, if necessary.

For the following two operators, automatic type conversions are notper-formed and, therefore, both the types and the values are compared.
2.6.4 Logical Operators
Logical operatorsfirst convert their operands to boolean values and then
perform the respective comparison.
Operator Name Value
== Equal to Checks for equality
between two arguments
performing type conver-sion when necessary:
1 == "1"results in true
1 == 1results in true
!= Not equal to Inverse of ==.
> Greater than Checks if first operand is
greater than second
< Smaller than Checks if first operand is
smaller than second
>= Greater than or equal to Checks if first operand is
greater or equal to second
<= Smaller than or equal to Checks if first operand
is smaller or equal to
second
Operator Name Value
=== Identical to Same as ==but the types
of the operands have to
match.
No automatic type conver-sions are performed:
1 === "1"results in
false.
1 === 1results in true.
!== Not identical to The inverse of ===.2.6.4 Logical Operators
Logical operatorsfirst convert their operands to boolean values and then
perform the respective comparison. 2.6.4.1 Short-Circuit Evaluation When evaluating the logical and/oropera-tors, you can often know the result without having to evaluate both operands.
For example, when PHP evaluates 0 && 1,it can tell the result will be false by
looking only at the left operand, and it won’t continue to evaluate the right
one. This might not seem useful right now, but later on, we’ll see how we can
use it to execute an operation only if a certain condition is met.
2.6.5 Bitwise Operators
Bitwise operatorsperform an operation on the bitwise representation of
their arguments. Unless the arguments are strings, they are converted to
their corresponding integer representation, and the operation is then per-formed. In case both arguments are strings, the operation is performed
between corresponding character offsets of the two strings (each character is
treated as an integer).

 2.6.6 Unary Operators
Unary operatorsact on one operand.
2.6.7 Negation Operators
Negation operatorsappear before their operand—for example, !$var (!is the
operator, $varis the operand).

2.6.8 Increment/Decrement Operators
Increment/decrement operatorsare unique in the sense that they operate
only on variables and not on any value. The reason for this is that in addition
to calculating the result value, the value of the variable itself changes as well.

As you can see from the previous table, there’s a difference in the value of
post- and pre-increment. However, in both cases, $varis incremented by 1. The
only difference is in the value to which the increment expression evaluates.
Example 1:
$num1 = 5;
$num2 = $num1++;// post-increment, $num2 is assigned $num1's original
➥value
print $num1; // this will print the value of $num1, which is now 6
print $num2; // this will print the value of $num2, which is the
➥original value of $num1, thus, 5Example 2:
$num1 = 5;
$num2 = ++$num1;// pre-increment, $num2 is assigned $num1's
➥incremented value
print $num1; // this will print the value of $num1, which is now 6
print $num2; // this will print the value of $num2, which is the
➥same as the value of $num1, thus, 6
The same rules apply to pre- and post-decrement.
2.6.8.1 Incrementing Strings Strings (when not numeric) are incremented
in a similar way to Perl. If the last letter is alphanumeric, it is incremented by
1. If it was ‘z’, ‘Z’, or ‘9’, it is incremented to ‘a’, ‘A’, or ‘0’ respectively, and the
next alphanumeric is also incremented in the same way. If there is no next
alphanumeric, one is added to the beginning of the string as ‘a’, ‘A’, and ‘1,’
respectively. If this gives you a headache, just try and play around with it.
You’ll get the hang of it pretty quickly.
Note:Non-numeric strings cannot be decremented.
2.6.9 The Cast Operators
PHP provides a C-like way to force a type conversion of a value by using the
cast operators. The operand appears on the right side of the cast operator,
and its result is the converted type according to the following table.
The casting operators change the type of a value and not the type of a
variable. For example:
$str = "5";
$num = (int) $str;
This results in $numbeing assigned the integer value of $str (5), but $str
remains of type string.2.6.10 The Silence Operator
The operator @silences error messages during the evaluation process of an
expression. It is discussed in more detail in Chapter 7.
2.6.11 The One and Only Ternary Operator
One of the most elegant operators is the ?:(question mark) operator. Its for-mat is
truth_expr ? expr1 : expr2
The operator evaluates truth_exprand checks whether it is true. If it is,
the value of the expression evaluates to the value of expr1(expr2is not evalu-ated). If it is false, the value of the expression evaluates to the value of expr2
(expr1is not evaluated).
For example, the following code snippet checks whether $ais set (using
isset()) and displays a message accordingly:
$a = 99;
$message = isset($a) ? '$a is set' : '$a is not set';
print $message;
This example prints the following:
$a is set

Data type of PHP

BASIC DATA TYPES
Eight different data types exist in PHP, five of which are scalar and each of the
remaining three has its own uniqueness. The previously discussed variables
can contain values of any of these data types without explicitly declaring their
type. The variable “behaves” according to the data type it contains.

2.5.1 IntegersIntegersare whole numbers and are equivalent in range as your C compiler’s
longvalue. On many common machines, such as Intel Pentiums, that means a
32-bit signed integer with a range between –2,147,483,648 to +2,147,483,647.
Integers can be written in decimal, hexadecimal (prefixed with 0x), and
octal notation (prefixed with 0), and can include +/-signs.
Some examples of integers include
240000
0xABCD


007
-100
Note:As integers are signed, the right shift operator in PHP always does a
signed shift.
2.5.2 Floating-Point Numbers
Floating-point numbers(also known as real numbers) represent real
numbers and are equivalent to your platform C compiler’s doubledata type.
On common platforms, the data type size is 8 bytes and it has a range of
approximately 2.2E–308 to 1.8E+308. Floating-point numbers include a deci-mal point and can include a +/-sign and an exponent value.
Examples of floating-point numbers include
3.14
+0.9e-2
-170000.5
54.6E42
2.5.3 Strings
Stringsin PHP are a sequence of characters that are always internally null-terminated. However, unlike some other languages, such as C, PHP does not
rely on the terminating null to calculate a string’s length, but remembers its
length internally. This allows for easy handling of binary data in PHP—for
example, creating an image on-the-fly and outputting it to the browser. The
maximum length of strings varies according to the platform and C compiler,
but you can expect it to support at least 2GB. Don’t write programs that test
this limit because you’re likely to first reach your memory limit.
When writing string values in your source code, you can use double
quotes ("), single quotes (') or here-docs to delimit them. Each method is
explained in this section. 2.5.3.1 Double Quotes Examples for double quotes:
"PHP: Hypertext Pre-processor"
"GET / HTTP/1.0\n"
"1234567890"
Strings can contain pretty much all characters. Some characters c
written as is, however, and require special notation:
An additional feature of double-quoted strings is that certain nota
variables and expressions can be embedded directly within them. W
going into specifics, here are some examples of legal strings that embe
ables. The references to variables are automatically replaced with th
ables’ values, and if the values aren’t strings, they are converted t
corresponding string representations (for example, the integer 123wo
first converted to the string "123").
"The result is $result\n"
"The array offset $i contains $arr[$i]"
In cases, where you’d like to concatenate strings with values (such
ables and expressions) and this syntax isn’t sufficient, you can use the .(do
ator to concatenate two or more strings. This operator is covered in a later 

2.5.3.1 Double Quotes Examples for double quotes:
"PHP: Hypertext Pre-processor"
"GET / HTTP/1.0\n"
"1234567890"
Strings can contain pretty much all characters. Some characters can’t be
written as is, however, and require special notation:An additional feature of double-quoted strings is that certain notations of
variables and expressions can be embedded directly within them. Without
going into specifics, here are some examples of legal strings that embed vari-
ables. The references to variables are automatically replaced with the vari-
ables’ values, and if the values aren’t strings, they are converted to their
corresponding string representations (for example, the integer 123would be
first converted to the string "123").
"The result is $result\n"
"The array offset $i contains $arr[$i]"
In cases, where you’d like to concatenate strings with values (such as vari-
ables and expressions) and this syntax isn’t sufficient, you can use the .(dot) oper-
ator to concatenate two or more strings. This operator is covered in a later section.
\n Newline.
\t Tab.
\" Double quote.
\\ Backslash.
\0 ASCII 0 (null).
\r Line feed.
\$ Escape $sign so that it is not treated as a variable but as the
character $.
\{Octal #} The character represented by the specified octal #—for exam-
ple, \70represents the letter 8.
\x{Hexadecimal #} The character represented by the specified hexadecimal #—for
example, \0x32represents the letter 2.

2.5.3.2 Single Quotes In addition to double quotes, single quotes m
delimit strings. However, in contrast to double quotes, single quotes
support all the double quotes’ escaping and variable substitution.
The following table includes the only two escapings supported by
quotes:
Newline.
Tab.
Double quote.
Backslash.
ASCII 0 (null).
Line feed.
Escape $sign so that it is not treated as a variable
character $.
tal #} The character represented by the specified octal #—
ple, \70represents the letter 8.
exadecimal #} The character represented by the specified hexadec
example, \0x32represents the letter 2.
Single quote.
Backslash, used when wanting to represent a back
lowed by a single quote—for example, \\'.Examples:
'Hello, World'
'Today\'s the day'
2.5.3.3 Here-Docs Here-docsenable you to embed large pieces of text in
your scripts, which may include lots of double quotes and single quotes, with-out having to constantly escape them.
The following is an example of a here-doc:
<<PHP stands for "PHP: Hypertext Preprocessor".
The acronym "PHP" is therefore, usually referred to as a recursive acronym
➥because the long form contains the acronym itself.
As this text is being written in a here-doc there is no need to escape the
➥double quotes.
THE_END
The strings starts with <<<, followed by a string that you know doesn’t
appear in your text. It is terminated by writing that string at the beginning of
a line, followed by an optional semicolon (;), and then a required newline (\n).
Escaping and variable substitution in here-docs is identical to double-quoted
strings except that you are not required to escape double quotes.
2.5.3.4 Accessing String Offsets Individual characters in a string can be
accessed using the $str{offset}notation. You can use it to both read and write
string offsets. When reading characters, this notation should be used only to
access valid indices. When modifying characters, you may access offsets that
don’t yet exist. PHP automatically sets that offset to the said character, and if
this results in a gap between the ending of the original string and the offset of
the new character, the gap filled with space characters (' ').
This example creates and prints the string "Andi"(in an awkward way):
$str = "A";
$str{2} = "d";
$str{1} = "n";
$str = $str . "i";
print $str;
Tip: For many cases, PHP has string manipulation functions which use effi-cient algorithms. You should first look at them before you access strings
directly using string offsets. They are usually prefixed with str_. For more
complex needs, the regular expressions functions—most notably the pcre_
family of functions—will come in handyThis support still exists in PHP 5, and you are likely to bump into it often.
However, you should really use the {}notation because it differentiates string
offsets from array offsets and thus, makes your code more readable.
2.5.4 Booleans
Booleans were introduced for the first time in PHP 4 and didn’t exist in prior
versions. A Boolean value can be either trueor false.
As previously mentioned, PHP automatically converts types when
needed. Boolean is probably the type that other types are most often converted
to behind the scenes. This is because, in any conditional code such as if state-ments, loops, and so on, types are converted to this scalar type to check if the
condition is satisfied. Also, comparison operators result in a Boolean value.
Consider the following code fragment:
$numerator = 1;
$denominator = 5;
if ($denominator == 0) {
print "The denominator needs to be a non-zero number\n";
}
The result of the equal-than operator is a Boolean; in this case, it would
be falseand, therefore, the if() statement would not be entered.
Now, consider the next code fragment:
$numerator = 1;
$denominator = 5;
if ($denominator) {
/* Perform calculation */
} else {
print "The denominator needs to be a non-zero number\n";
}
You can see that no comparison operator was used in this example; how-ever, PHP automatically internally converted $denominatoror, to be more accu-rate, the value 5to its Boolean equivalent, true, to perform the if()statement
and, therefore, enter the calculation.
Although not all types have been covered yet, the following table shows
truth values for their values. You can revisit this table to check for the types of
Boolean value equivalents, as you learn about the remaining types.2.5.5 Null
Nullis a data type with only one possible value: the NULLvalue. It marks vari-
ables as being empty, and it’s especially useful to differentiate between the
empty string and null values of databases.
The isset($variable)operator of PHP returns falsefor NULL, and truefor
any other data type, as long as the variable you’re testing exists.
The following is an example of using NULL:
$value = NULL;
2.5.6 Resources
Resources, a special data type, represent a PHP extension resource such as a
database query, an open file, a database connection, and lots of other external
types.
You will never directly touch variables of this type, but will pass them
around to the relevant functions that know how to interact with the specified
resource.
2.5.7 Arrays
An arrayin PHP is a collection of key/value pairs. This means that it maps
keys (or indexes) to values. Array indexescan be either integers or strings
whereas values can be of any type (including other arrays).
Tip:Arrays in PHP are implemented using hash tables, which means that
accessing a value has an average complexity of O(1).
2.5.7.1array()construct Arrays can be declared using the array()lan-
guage construct, which generally takes the following form (elements inside
square brackets, [], are optional):
array([key =>] value, [key =>] value, ...)
Data Type False Values True Values
Integer 0 All non-zero values
Floating point 0.0 All non-zero values
Strings Empty strings ()""
The zero string ()"0"
All other strings
Null Always Never
Array If it does not contain
any elements
If it contains at least
one element
Object Never Always
Resource Never AlwaysThe key is optional, and when it’s not specified, the key is automatically
assigned one more than the largest previous integer key (starting with 0). You
can intermix the use with and without the key even within the same declara-tion.
The value itself can be of any PHP type, including an array. Arrays con-taining arrays give a similar result as multi-dimensional arrays in other lan-guages.
Here are a few examples:
☞array(1, 2, 3)is the same as the more explicit array(0 => 1, 1 => 2, 2
➥=> 3).
☞array("name" => "John", "age" => 28)
☞array(1 => "ONE", "TWO", "THREE")is equivalent to array(1 => "ONE", 2 =>
➥"TWO", 3 => "THREE").
☞array() an empty array.
Here’s an example of a nested array()statement:
array(array("name" => "John", "age" => 28), array("name" =>
➥"Barbara", "age" => 67))
The previous example demonstrates an array with two elements: Each
one is a collection (array) of a person’s information.
2.5.7.2 Accessing Array Elements Array elements can be accessed by using
the $arr[key]notation, where keyis either an integer or string expression.
When using a constant string for key,make sure you don’t forget the single or
double quotes, such as $arr["key"]. This notation can be used for both reading
array elements and modifying or creating new elements.
2.5.7.3 Modifying/Creating Array Elements
$arr1 = array(1, 2, 3);
$arr2[0] = 1;
$arr2[1] = 2;
$arr2[2] = 3;
print_r($arr1);
print_r($arr2);
The print_r()function has not been covered yet in this book, but when it
is passed an array, it prints out the array’s contents in a readable way. You can
use this function when debugging your scripts.
The previous example prints
Array
(
[0] => 1[1] => 2
[2] => 3
)
Array
(
[0] => 1
[1] => 2
[2] => 3
)
So, you can see that you can use both the array()construct and the
$arr[key] notation to create arrays. Usually, array()is used to declare arrays
whose elements are known at compile-time, and the $arr[key]notation is used
when the elements are only computed at runtime.
PHP also supports a special notation, $arr[], where the key is not speci-
fied. When creating new array offsets using this notation (fo example, using it
as the l-value), the key is automatically assigned as one more than the largest
previous integer key.
Therefore, the previous example can be rewritten as follows:
$arr1 = array(1, 2, 3);
$arr2[] = 1;
$arr2[] = 2;
$arr2[] = 3;
The result is the same as in the previous example.
The same holds true for arrays with string keys:
$arr1 = array("name" => "John", "age" => 28);
$arr2["name"] = "John";
$arr2["age"] = 28;
if ($arr1 == $arr2) {
print '$arr1 and $arr2 are the same' . "\n";
}
The message confirming the equality of both arrays is printed.
2.5.7.4 Reading array values You can use the $arr[key]notation to read
array values. The next few examples build on top of the previous example:
print $arr2["name"];
if ($arr2["age"] < 35) {
print " is quite young\n";
}This example prints
John is quite young
Note:As previously mentioned, using the $arr[]syntax is not supported
when reading array indexes, but only when writing them.
2.5.7.5 Accessing Nested Arrays (or Multi-Dimensional Arrays) When
accessing nested arrays, you can just add as many square brackets as required
to reach the relevant value. The following is an example of how you can
declare nested arrays:
$arr = array(1 => array("name" => "John", "age" => 28), array("name"
➥=> "Barbara", "age" => 67))
You could achieve the same result with the following statements:
$arr[1]["name"] = "John";
$arr[1]["age"] = 28;
$arr[2]["name"] = "Barbara";
$arr[2]["age"] = 67;
Reading a nested array value is trivial using the same notation. For
example, if you want to print John’s age, the following statement does the
trick:
print $arr[1]["age"];
2.5.7.6 Traversing Arrays Using foreach There are a few different ways of
iterating over an array. The most elegant way is the foreach()loop construct.
The general syntax of this loop is
foreach($array as [$key =>] [&] $value)
...
$keyis optional, and when specified, it contains the currently iterated
value’s key, which can be either an integer or a string value, depending on the
key’s type.
Specifying &for the value is also optional, and it has to be done if you are
planning to modify $valueand want it to propagate to $array.In most cases,
you won’t want to modify the $valuewhen iterating over an array and will,
therefore, not need to specify it.Here’s a short example of the foreach()loop:
$players = array("John", "Barbara", "Bill", "Nancy");
print "The players are:\n";
foreach ($players as $key => $value) {
print "#$key = $value\n";
}
The output of this example is
The players are:
#0 = John
#1 = Barbara
#2 = Bill
#3 = Nancy
Here’s a more complicated example that iterates over an array of people
and marks which person is considered old and which one is considered young:
$people = array(1 => array("name" => "John", "age" => 28),
➥array("name" => "Barbara", "age" => 67));
foreach ($people as &$person) {
if ($person["age"] >= 35) {
$person["age group"] = "Old";
} else {
$person["age group"] = "Young";
}
}
print_r($people);
Again, this code makes use of the print_r()function.
The output of the previous code is the following:
Array
(
[1] => Array
(
[name] => John
[age] => 28
[age group] => Young
)
[2] => Array
(
[name] => Barbara
[age] => 67
[age group] => Old)
)
You can see that both the John and Barbara arrays inside the $people
array were added an additional value with their respective age group.
2.5.7.7 Traversing Arrays Using list()and each()  Although foreach()
is the nicer way of iterating over an array, an additional way of traversing an
array is by using a combination of the list()construct and the each()func-
tion:
$players = array("John", "Barbara", "Bill", "Nancy");
reset($players);
while (list($key, $val) = each($players)) {
print "#$key = $val\n";
}
The output of this example is
#0 = John
#1 = Barbara
#2 = Bill
#3 = Nancy
2.5.7.8reset() Iteration in PHP is done by using an internal array pointer
that keeps record of the current position of the traversal. Unlike with
foreach(), when you want to use each()to iterate over an array, you must
reset()the array before you start to iterate over it. In general, it is best for
you to always use foreach()and not deal with this subtle nuisance of each()
traversal.
2.5.7.9each() The each()function returns the current key/value pair and
advances the internal pointer to the next element. When it reaches the end
of of the array, it returns a booloean value of false. The key/value pair is
returned as an array with four elements: the elements 0and "key", which
have the value of the key, and elements 1and "value", which have the value
of the value. The reason for duplication is that, if you’re accessing these ele-
ments individually, you’ll probably want to use the names such as
$elem["key"]and $elem["value"]:
$ages = array("John" => 28, "Barbara" => 67);
reset($ages);
$person = each($ages);print $person["key"];
print " is of age ";
print $person["value"];
This prints
John is of age 28
When we explain how the list()construct works, you will understand
why offsets 0 and 1 also exist.
2.5.7.10list() The list()construct is a way of assigning multiple array
offsets to multiple variables in one statement:
list($var1, $var2, ...) = $array;
The first variable in the list is assigned the array value at offset 0, the
second is assigned offset 1, and so on. Therefore, the list()construct trans-lates into the following series of PHP statements:
$var1 = $array[0];
$var2 = $array[1];
...
As previously mentioned, the indexes 0 and 1 returned by each()are
used by the list()construct. You can probably already guess how the combi-nation of list()and each()work.
Consider the highlighted line from the previous $playerstraversal example:
$players = array("John", "Barbara", "Bill", "Nancy");
reset($players);
while (list($key, $val) = each($players)) {
print "#$key = $val\n";
}
What happens in the boldfaced line is that during every loop iteration,
each()returns the current position’s key/value pair array, which, when exam-ined with print_r(), is the following array:
Array
(
[1] => John
[value] => John[0] => 0
[key] => 0
)
Then, the list()construct assigns the array’s offset 0 to $keyand offset 1
to $val.
2.5.7.11 Additional Methods for Traversing Arrays You can use other func-tions to iterate over arrays including current()and next(). You shouldn’t use
them because they are confusing and are legacy functions. In addition, some
standard functions allow all sorts of elegant ways of dealing with arrays such
as array_walk(), which is covered in a later chapter.
2.5.8 Constants
In PHP, you can define names, called constants, for simple values. As the
name implies, you cannot change these constants once they represent a cer-tain value. The names for constants have the same rules as PHP variables
except that they don’t have the leading dollar sign. It is common practice in
many programming languages—including PHP—to use uppercase letters for
constant names, although you don’t have to. If you wish, which we do not rec-ommend, you may define your constants as case-insensitive, thus not requir-ing code to use the correct casing when referring to your constants.
Tip:Only use case-sensitive constants both to be consistent with accepted cod-ing standards and because it is unclear if case-insensitive constants will con-tinued to be supported in future versions of PHP.
Unlike variables, constants, once defined, are globally accessible. You
don’t have to (and can’t) redeclare them in each new function and PHP file.
To define a constant, use the following function:
define("CONSTANT_NAME", value [, case_sensitivity])
Where:
☞"CONSTANT_NAME"is a string.
☞valueis any valid PHP expression excluding arrays and objects.
☞case_sensitivityis a Boolean (true/false) and is optional. The default is
true.
An example for a built-in constant is the Boolean value true, which is
registered as case-insensitive.
Here’s a simple example for defining and using a constant:

PHP veriables

VARIABLES
Variables in PHP are quite different from compiled languages such as C and
Java. This is because their weakly typed nature, which in short means you
don’t need to declare variables before using them, you don’t need to declare
their type and, as a result, a variable can change the type of its value as much
as you want.
Variables in PHP are preceded with a $sign, and similar to most modern
languages, they can start with a letter (A-Za-z) or _(underscore) and can then
contain as many alphanumeric characters and underscores as you like.
Examples of legal variable names include
$count
$_Obj
$A123
Example of illegal variable names include
$123
$*ABC
As previously mentioned, you don’t need to declare variables or their
type before using them in PHP. The following code example uses variables:
$PI = 3.14;
$radius = 5;
$circumference = $PI * 2 * $radius; // Circumference = π* d
You can see that none of the variables are declared before they are used.
Also, the fact that $PIis a floating-point number, and $radius(an integer) is
not declared before they are initialized.
PHP does not support global variables like many other programming
languages (except for some special pre-defined variables, which we discuss
later). Variables are local to their scope, and if created in a function, they are
only available for the lifetime of the function. Variables that are created in
the main script (not within a function) aren’t global variables; you cannot sethem inside functions, but you can access them by using a special array
$GLOBALS[], using the variable’s name as the string offset. The previous
example can be rewritten the following way:
$PI = 3.14;
$radius = 5;
$circumference = $GLOBALS["PI"] * 2 * $GLOBALS["radius"];
➥// Circumference = π* d
You might have realized that even though all this code is in the main
scope (we didn’t make use of functions), you are still free to use $GLOBALS[],
although in this case, it gives you no advantage. 
Indirect References to Variables
An extremely useful feature of PHP is that you can access variables by using
indirect references, or to put it simply, you can create and access variables by
name at runtime.
Consider the following example:
$name = "John";
$$name = "Registered user";
print $John;
This code results in the printing of "Registered user."
The bold line uses an additional $to access the variable with name speci-fied by the value of $name("John") and changing its value to "Registered user".
Therefore, a variable called $Johnis created.
You can use as many levels of indirections as you want by adding addi-tional $signs in front of a variable.
.Managing Variables
Three language constructs are used to manage variables. They enable you to
check if certain variables exist, remove variables, and check variables’ truth
values.
2.4.2.1isset() isset()determines whether a certain variable has already
been declared by PHP. It returns a boolean value trueif the variable has
already been set, and falseotherwise, or if the variable is set to the value NULL.
Consider the following script:
if (isset($first_name)) {
print '$first_name is set';
}
This code snippet checks whether the variable $first_nameis defined. If
$first_nameis defined, isset()returns true, which will display '$first_name is
set.' If it isn’t, no output is generatedthem inside functions, but you can access them by using a special array
$GLOBALS[], using the variable’s name as the string offset. The previous
example can be rewritten the following way:
$PI = 3.14;
$radius = 5;
$circumference = $GLOBALS["PI"] * 2 * $GLOBALS["radius"];
➥// Circumference = π* d
You might have realized that even though all this code is in the main
scope (we didn’t make use of functions), you are still free to use $GLOBALS[],
although in this case, it gives you no advantage.2.4.2.2unset() unset()“undeclares” a previously set variable, and frees
any memory that was used by it if no other variable references its value. A call
to isset() on a variable that has been unset()returns false.
For example:
$name = "John Doe";
unset($name);
if (isset($name)) {
print ’$name is set';
}
This example will not generate any output, because isset()returns
false.
unset()can also be used on array elements and object properties similar
to isset().2.4.2.3empty() empty() may be used to check if a variable has not been
declared or its value is false. This language construct is usually used to check
if a form variable has not been sent or does not contain data. When checking a
variable’s truth value, its value is first converted to a Boolean according to the
rules in the following section, and then it is checked for true/false.
For example:
if (empty($name)) {
print 'Error: Forgot to specify a value for $name';
}
This code prints an error message if $namedoesn’t contain a value that
evaluates to true. 
Superglobals
As a general rule, PHP does not support global variables (variables that can
automatically be accessed from any scope). However, certain special internal
variables behave like global variables similar to other languages. These vari-ables are called superglobalsand are predefined by PHP for you to use. Some
examples of these superglobals are
☞$_GET[]. An array that includes all the GETvariables that PHP received
from the client browser.
☞$_POST[]. An array that includes all the POSTvariables that PHP received
from the client browser.
☞$_COOKIE[]. An array that includes all the cookies that PHP received from
the client browser.
☞$_ENV[]. An array with the environment variables.
☞$_SERVER[]. An array with the values of the web-server variables.
These superglobals and others are detailed in Chapter 5, “How to Write a
Web Application with PHP.” On a language level, it is important to know that
you can access these variables anywhere in your script whether function,
method, or global scope. You don’t have to use the $GLOBALS[]array, which
allows for accessing global variables without having to predeclare them or
using the deprecated globalskeyword.

other Feature in php 5

1.4 OTHER NEW FEATURES IN PHP 5
This section discusses new features introduced in PHP 5.
1.4.1 New Memory Manager
The Zend Engine features a new memory manager. The two main advantages
are better support for multi-threaded environments (allocations do not need to
perform any mutual exclusion locks), and after each request, freeing the allo-cated memory blocks is more efficient. Because this is an underlying infra-structure change, you will not notice it directly as the end user.

1.4.2 Dropped Support for Windows 95
Running PHP on the Windows 95 platform is not supported anymore due to
Windows 95 does not support the functionality that PHP uses. Because
Microsoft officially stopped supporting it in 2002, the PHP development com-munity decided that dropping the support was a wise decision.

GENERALPHP CHANGES in PHP 5

GENERALPHP CHANGES in PHP 5
1.3.1 XML and Web Services

Following the changes in the language, the XML updates in PHP 5 are proba-
bly the most significant and exciting. The enhanced XML functionality in PHP
5 puts it on par with other web technologies in some areas and overtakes them
in others.
1.3.1.1 The Foundation
XML support in PHP 4 was implemented using a
variety of underlying XML libraries. SAX support was implemented using the
old Expat library, XSLT was implemented using the Sablotron library (or using
libxml2 via the DOM extension), and DOM was implemented using the more
powerful libxml2 library by the GNOME project.
Using a variety of libraries did not make PHP 4 excel when it came to
XML support. Maintenance was poor, new XML standards were not always
supported, performance was not as good as it could have been, and interopera-
bility between the various XML extensions did not exist.
In PHP 5, all XML extensions have been rewritten to use the superb
libxml2 XML toolkit (http://www.xmlsoft.org/). It is a feature-rich, highly main-
tained, and efficient implementation of the XML standards that brings cutting-
edge XML technology to PHP.

All the afore-mentioned extensions (SAX, DOM, and XSLT) now use
libxml2, including the new additional extensions SimpleXML and SOAP.
1.3.1.2 SAX As previously mentioned, the new SAX implementation has
switched from using Expat to libxml2. Although the new extension should be
compatible, some small subtle differences might exist. Developers who still
want to work with the Expat library can do so by configuring and building
PHP accordingly (which is not recommended).
1.3.1.3 DOM Although DOM support in PHP 4 was also based on the libxml2
library, it had bugs, memory leaks, and in many cases, the API was not W3C-compliant. The DOM extension went through a thorough facelift for PHP 5. Not
only was the extension mostly rewritten, but now, it is also W3C-compliant. For
example, function names now use studlyCapsas described by the W3C standard,
which makes it easier to read general W3C documentation and implement what
you have learned right away in PHP. In addition, the DOM extension now sup-ports three kinds of schemas for XML validation: DTD, XML schema, and
RelaxNG.
As a result of these changes, PHP 4 code using DOM will not always run
in PHP 5. However, in most cases, adjusting the function names to the new
standard will probably do the trick.
1.3.1.4 XSLT In PHP 4, two extensions supported XSL Transformations: the
Sablotron extension and the XSLT support in the DOM extension. PHP 5 fea-tures a new XSL extension and, as previously mentioned, it is based on the
libxml2 extension. As in PHP 5, the XSL Transformation does not take the
XSLT stylesheet as a parameter, but depends on the DOM extension to load it.
The stylesheet can be cached in memory and may be applied to many docu-ments, which saves execution time.
1.3.1.5 SimpleXML When looking back in a year or two, it will be clear that
SimpleXML revolutionized the way PHP developers work with XML files.
Instead of having to deal with DOM or—even worse—SAX, SimpleXML repre-sents your XML file as a native PHP object. You can read, write, or iterate over
your XML file with ease, accessing elements and attributes.
Consider the following XML file:


John Doe
87234838


Janet Smith
72384329

The following code prints each client’s name and account number:
$clients = simplexml_load_file('clients.xml');
foreach ($clients->client as $client) {
print "$client->name has account number $client
➥>account_number\n";
}
It is obvious how simple SimpleXML really is.
In case you need to implement an advanced technique in your Sim-pleXML object that is not supported in this lightweight extension, you can
convert it to a DOM tree by calling it dom_import_simplexml(), manipulate it in
DOM, and convert it to SimpleXML using simplexml_import_dom().
Thanks to both extensions using the same underlying XML library,
switching between them is now a reality.
1.3.1.6 SOAP PHP 4 lacked official native SOAP support. The most com-monly used SOAP implementation was PEARs, but because it was imple-mented entirely in PHP, it could not perform as well as a built-in C extension.
Other available C extensions never reached stability and wide adoption and,
therefore, were not included in the main PHP 5 distribution.
SOAP support in PHP 5 was completely rewritten as a C extension and,
although it was only completed at a very late stage in the beta process, it was
incorporated into the default distribution because of its thorough implementa-tion of most of the SOAP standard.
The following calls SomeFunction()defined in a WSDL file:
$client = new SoapClient("some.wsdl");
$client->SomeFunction($a, $b, $c);
1.3.1.7 New MySQLi (MySQL Improved) Extension For PHP 5, MySQL AB
(http://www.mysql.com) has written a new MySQL extension that enables you
to take full advantage of the new functionality in MySQL 4.1 and later. As
opposed to the old MySQL extension, the new one gives you both a functional
and an OO interface so that you can choose what you prefer. New features sup-ported by this extension include prepared statements and variable binding,
SSL and compressed connections, transaction control, replication support, and
more.
1.3.1.8 SQLite Extension Support for SQLite (http://www.sqlite.org) was
first introduced in the PHP 4.3.x series. It is an embedded SQL library that
does not require an SQL server, so it is suitable for applications that do not
require the scalability of SQL servers or, if you deploy at an ISP that does notoffer access to an SQL server. Contrary to what its name implies, SQLite has
many features and supports transactions, sub-selects, views, and large data-base files. It is mentioned here as a PHP 5 feature because it was introduced
so late in the PHP 4 series, and because it takes advantage of PHP 5 by pro-viding an OO interface and supporting iterators.
1.3.1.9 Tidy Extension PHP 5 includes support for the useful Tidy (http://
tidy.sf.net/) library. It enables PHP developers to parse, diagnose, clean, and
repair HTML documents. The Tidy extension supports both a functional and
an OO interface, and its API uses the PHP 5 exception mechanism.
1.3.1.10 Perl Extension Although not bundled in the default PHP 5 package,
the Perl extension allows you to call Perl scripts, use Perl objects, and use
other Perl functionality natively from within PHP. This new extension sits
within the PECL (PHP Extension Community Library) repository at http://
pecl.php.net/package/perl.

Features of PHP 5

Language Features
For a more complete example, see Chapter 4, “PHP 5 Advanced OOP and
Design Patterns.”
☞__autoload().
Many developers writing object-oriented applications create one PHP
source file per class definition. One of the biggest annoyances is having to
write a long list of needed inclusions at the beginning of each script (one for
each class). In PHP 5, this is no longer necessary. You may define an
__autoload()function that is automatically called in case you are trying to use
a class that has not been defined yet. By calling this function, the scripting
engine offers one last chance to load the class before PHP bails out with an
error:
function __autoload($class_name) {
include_once($class_name . "php");
}
$obj = new MyClass1();
$obj2 = new MyClass2();
Other New Language Features
☞Exception handling.
PHP 5 adds the ability for the well-known try/throw/catchstructured
exception-handling paradigm. You are only allowed to throw objects that
inherit from the Exceptionclass:
class SQLException extends Exception {
public $problem;
function __construct($problem) {
$this->problem = $problem;
}
}
try {
...
throw new SQLException("Couldn't connect to database");
...
} catch (SQLException $e) {
print "Caught an SQLException with problem $obj->problem";
} catch (Exception $e) {
print "Caught unrecognized exception";
}
Currently for backward-compatibility purposes, most internal functions
do not throw exceptions. However, new extensions make use of this capability,
and you can use it in your own source code. Also, similar to the already exist-ing set_error_handler(), you may use set_exception_handler()to catch an
unhandled exception before the script terminates.
Gutmans_Ch01 Page 7 Thursday, September 23, 2004 2:35 PM
8  What Is New in PHP 5? Chap. 1
☞foreachwith references.
In PHP 4, you could not iterate through an array and modify its values.
PHP 5 supports this by enabling you to mark the foreach()loop with the
&(reference) sign, which makes any values you change affect the array
over which you are iterating:
foreach ($array as &$value) {
if ($value === "NULL") {
$value = NULL;
}
}
☞Default values for by-reference parameters.
In PHP 4, default values could be given only to parameters, which are
passed by-values. PHP 5 now supports giving default values to by-reference parameters:
function my_func(&$arg = null) {
if ($arg === NULL) {
print '$arg is empty';
}
}
my_func();

PHP 5

1  PHP 5

1.1 INTRODUCTION
                 Only time will tell if the PHP 5 release will be as successful as its two prede- cessors (PHP 3 and PHP 4). The new features and changes aim to rid PHP of any weaknesses it may have had and make sure that it stays in the lead as the world’s best web-scripting language. This book details PHP 5 and its new features. However, if you are familiar with PHP 4 and are eager to know what is new in PHP 5, this chapter is for you. When you finish reading this chapter, you will have learned ☞The new language features ☞News concerning PHP extensions ☞Other noteworthy changes to PHP’s latest version  
1.2  LANGUAGE FEATURES 
1.2.1 New Object-Oriented Model 
When Zeev Suraski added the object-oriented syntax back in the days of PHP 3, it was added as “syntactic sugar for accessing collections.” The OO model also had support for inheritance and allowed a class (and object) to aggregate both methods and properties, but not much more. When Zeev and Andi Gut- mans rewrote the scripting engine for PHP 4, it was a completely new engine; it ran much faster, was more stable, and boasted more features. However, the OO model first introduced in PHP 3 was barely touched. Although the object model had serious limitations, it was used exten- sively around the world, often in large PHP applications. This impressive use of the OOP paradigm with PHP 4, despite its weaknesses, led to it being the main focus for the PHP 5 release.So, what were some of the limitations in PHP 3 and 4? The biggest limi-tation (which led to further limitations) was the fact that the copy semantics of
objects were the same as for native types. So, how did this actually affect the
PHP developer? When assigning a variable (that points to an object) to
another variable, a copy of the object would be created. Not only did this
impact performance, but it also usually led to obscure behavior and bugs in
PHP 4 applications because many developers thought that both variables
would point at the same object, which was not the case. The variables were
instead pointing at separate copies of the same object. Changing one would
not change the other.
For example:
class Person {
var $name;
function getName()
{
return $this->name;
}
function setName($name)
{
$this->name = $name;
}
function Person($name)
{
$this->setName($name);
}
}
function changeName($person, $name)
{
$person->setName($name);
}
$person = new Person("Andi");
changeName($person, "Stig");
print $person->getName();
In PHP 4, this code would print out "Andi". The reason is that we pass
the object $personto the changeName()function by-value, and thus, $personis
copied and changeName()works on a copy of $person.
This behavior is not intuitive, as many developers would expect the Java-like behavior. In Java, variables actually hold a handle (or pointer) to the
object, and therefore, when it is copied, only the handle (and not the entire
object) is duplicated.
There were two kinds of users in PHP 4: the ones who were aware of this
problem and the ones who were not. The latter would usually not notice this
problem and their code was written in a way where it did not really matter if
the problem existed. Surely some of these people had sleepless nights trying to
track down weird bugs that they could not pinpoint. The former group dealt
with this problem by always passing and assigning objects by reference. This
would prevent the engine from copying their objects, but it would be a head-ache because the code included numerous & signs.The old object model not only led to the afore-mentioned problems, but
also to fundamental problems that prevented implementing some additional
features on top of the existing object model.
In PHP 5, the infrastructure of the object model was rewritten to work
with object handles. Unless you explicitly clone an object by using the clone
keyword, you never create behind-the-scenes duplicates of your objects. In
PHP 5, you don’t need a need to pass objects by reference or assign them by
reference.
Note:Passing by reference and assigning by reference are still sup-ported, in case you want to actually change a variable’s content (whether
object or other type).
1.2.2 New Object-Oriented Features
The new OO features are too numerous to give a detailed description in this
section. Chapter 3, “PHP 5 OO Language,” details each feature.
The following list provides the main new features:
☞public/private/protectedaccess modifiers for methods and properties.
Allows the use of common OO access modifiers to control access to
methods and properties:
class MyClass {
private $id = 18;
public function getId() {
return $this->id;
}
}
☞Unified constructor name __construct().
Instead of the constructor being the name of the class, it is now declared
as __construct(), which makes it easier to shift classes inside class hier-archies:
class MyClass {
function __construct() {
print "Inside constructor";
}
}
☞Object destructor support by defining a __destructor() method.
Allows defining a destructor function that runs when an object
is destroyed:
class MyClass {
function __destruct() {
print ”Destroying object”;
}
}
Gutmans_Ch01 Page 3 Thursday, September 23, 2004 2:35 PM
4  What Is New in PHP 5? Chap. 1
☞Interfaces.
Gives the ability for a class to fulfill more than one is-a relationships. A class can
inherit only from one class, but may implement as many interfaces as it wants:
interface Display {
function display();
}
class Circle implements Display {
function display() {
print "Displaying circle\n";
}
}
☞instanceofoperator.
Language-level support for is-a relationship checking. The PHP 4 is_a() function
is now deprecated:
if ($obj instanceof Circle) {
print '$obj is a Circle';
}
☞Final methods.
The finalkeyword allows you to mark methods so that an inheriting class cannot overload
them:
class MyClass {
final function getBaseClassName() {
return __CLASS__;
}
}
☞Final classes.
After declaring a class as final, it cannot be inherited. The following example
would error out.
final class FinalClass {
}
class BogusClass extends FinalClass {
}
☞Explicit object cloning.
To clone an object, you must use the clonekeyword. You may declare a __clone()
method, which will be called during the clone process (after the properties have
been copied from the original object):
Gutmans_Ch01 Page 4 Thursday, September 23, 2004 2:35 PM
1.2 Language Features 5
class MyClass {
function __clone() {
print "Object is being cloned";
}
}
$obj = new MyClass();
$obj_copy = clone $obj;
☞Class constants.
Class definitions can now include constant values and are referenced
using the class:
class MyClass {
const SUCCESS = "Success";
const FAILURE = "Failure";
}
print MyClass::SUCCESS;
☞Static methods.
You can now define methods as static by allowing them to be called from
non-object context. Static methods do not define the $thisvariable
because they are not bound to any specific object:
class MyClass {
static function helloWorld() {
print "Hello, world";
}
}
MyClass::helloWorld();
☞Static members.
Class definitions can now include static members (properties) that are
accessible via the class. Common usage of static members is in the
Singleton pattern:
class Singleton {
static private $instance = NULL;
private function __construct() {
}
static public function getInstance() {
if (self::$instance == NULL) {
self::$instance = new Singleton();
}
return self::$instance;
}
}
Gutmans_Ch01 Page 5 Thursday, September 23, 2004 2:35 PM
6  What Is New in PHP 5? Chap. 1
☞Abstract classes.
A class may be declared abstractto prevent it from being instantiated.
However, you may inherit from an abstract class:
abstract class MyBaseClass {
function display() {
print "Default display routine being called";
}
}
☞Abstract methods.
A method may be declared abstract, thereby deferring its definition to an
inheriting class. A class that includes abstract methods must be declared
abstract:
abstract class MyBaseClass {
abstract function display();
}
☞Class type hints.
Function declarations may include class type hints for their parameters.
If the functions are called with an incorrect class type, an error occurs:
function expectsMyClass(MyClass $obj) {
}
☞Support for dereferencing objects that are returned from methods.
In PHP 4, you could not directly dereference objects that were returned
from methods. You had to first assign the object to a dummy variable and
then dereference it.
PHP 4:
$dummy = $obj->method();
$dummy->method2();
PHP 5:
$obj->method()->method2();
☞Iterators.
PHP 5 allows both PHP classes and PHP extension classes to implement
an Iteratorinterface. After you implement this interface, you can iterate
instances of the class by using the foreach()language
construct:
$obj = new MyIteratorImplementation();
foreach ($obj as $value) {
print "$value";
}
Gutmans_Ch01 Page 6 Thursday, September 23, 2004 2:35 PM