Cover
Copyright
Contents
Reference
Index
previous
next
Contents:
- 2. CONCEPTS
- 2.1 Page structure
2.2 Data types and structures
- 2.2.1 Raw data types
2.2.2 Data structures
2.2.3 Data type treatment
2.3 Variables
- 2.3.1 Variable names and data types
2.3.2 Arrays
2.3.3 The scope of a variable
2.3.4 Superglobal arrays
2.3.5 Static variables
2.3.6 Variable reference
-
Assigning a variable by reference
Passing a variable by reference
Reference to a function
Reference and the static and global properties
Reference Insight
2.4 Named constants
- 2.4.1 Constant values
2.4.2 Constant names
2.4.3 Constant definition
2.4.4 Constant visibility
2.4.5 Some constant functions
2.5 Operators
- 2.5.1 Operator description
- Scalar operators
Bitwise operators
Array operators
Class operators
Assignment operators
Control operators
2.5.2 Precedence
2.5.3 Associativity
2.6 Expressions
- 2.6.1 What an expression is
2.6.2 Expression type and value
2.6.3 More on expression evaluation
2.7 Control structures
- 2.7.1 The if statement
2.7.2 The switch statement
2.7.3 The while statements
2.7.4 The do ... while
2.7.5 The foreach statement
2.7.6 The for statement
2.7.7 Other statements
2.8 Functions
- 2.8.1 Function definition and function call
2.8.2 Argument passing by value vs by reference
2.8.3 Argument default value
2.8.4 Returned value
2.8.5 Dependent definition
2.8.6 Including user function libraries
2.8.7 PHP functions
2.9 PHP core functions
- 2.9.1 String functions
2.9.2 Date and time functions
2.9.3 Array functions
2.9.4 File system functions
2.9.5 Variable functions
2.9.6 PHP options and informations
2.9.7 Miscellaneous functions
- The eval function
Script execution control
Constant functions
Pack and unpack
2.10 Class and object
- 2.10.1 The concepts of class and object
2.10.2 Programming aspects
- Class definition
Object creation
Using an object
Object destruction
2.10.3 Class extension
2.10.4 Encapsulation
2.10.5 Static and constant members
2.10.6 Miscellany
- __autoload
A PHP page is intended for the generation of a presentation page to be sent to the client side. Currently, the PHP would generate an HTML page, by default. But you can try this page that uses a style sheet(TestXmlPage.php with TestXml.css, both in the samples directory):
<?php
print("<?xml version='1.0' ?>\n");
print("<?xml-stylesheet type='text/css'
href='TestXml.css' ?>\n");
?>
<!DOCTYPE docu [
<!ELEMENT docu (para*)>
<!ELEMENT PARA (#PCDATA)>
]>
<docu>
<para>
<?php
print "Hello WORLD!";
?>
</para>
</docu>
| The style sheet has the following contents:
para {font-weight:bold; color:red;}
|
This page starts with 2 PHP print sequences which writes out the XML declaration and stylesheet declaration lines of an XML page. And the rest of the page is also XML.
You can call this page from a browser as shown in the preceding chapter. From this page an XML page is generated, which takes into account the style sheet (TestXml.css) that directs the text to be displayed in red bold characters.
If you installed the Apache server as suggested, please click here to see the result.
To further check that the page is processed as an XML page, you can add the following line between the </para> and the </docu> tags:
<para>unbalanced para tag
This will cause a parsing error as is expected with an XML page, whereas with HTML 4, the <para> tag is ignored.
|
A PHP page is a page of HTML or XML code interspersed with PHP sequences. Or it can be entirely made of one PHP sequence. All this was seen in the preceding chapter (2.1 How a PHP page is processed) and need not be further elaborated.
2.2 Data types and structures |
In PHP, a data has a type. However variables are not assigned a definite data type, but takes on the type of the last datum assigned to it. Moreover, a data of a given type can be treated as one of any other type, e.g. a character string can be used in an arithmetic operation, or tested for its boolean value.
2.2.1 Raw data types
The data types can be categorized as:
- scalar
- special
The scalar types include:
- boolean data | which can take on the values true or false (case insensitive, i.e. can be TRUE, True, etc.)
|
- integer data | which represent integers, the range of which is platform dependent (usually, -2147463648 to +2147483647)
|
- float data | (also known as real number or double) which represent floating point numbers. These can be represented with or without an exponent noted "e" or "E":
123.55 | without exponent
| 1.2345E+2 | with positive exponent
| 12345.e-2 | with negative exponent
|
|
- string data | which represent character strings. A string of data can be enclosed within:
single quotes | the $ within single quotes are treated as data, which is part of the data string
| double quotes | the $ within double quotes are considered to be the start of a variable name, and in evaluating the string value, the variable name is replaced by the value of the variable.
|
Example: $var = "abcd";
print ('This string: $var'); | result: This string: $var
| print ("This string: $var"); | result: This string: abcd
|
A multiple line string data can be represented using the so-called heredoc syntax. Example:
$text = <<<EOB
This text has multiple lines
The semi-colon ends the assignment statement
EOB is a user chosen word
EOB; |
In this example:
<<< | the triple < sign introduces the multi-line bloc
| EOB | is a user chosen word that will be used to close the multi-line bloc
| | The closing EOB word is the one which stands alone at the beginning of its line (not the one which is followed by other characters on its line).
|
|
The special data types include:
- the resource data |
|
- the null data |
|
The resource data type represents the complex data returned by some functions. Examples:
the | fopen | function returns a data structure called a handle that contains informations on the opened file, to be used by some of the file processing functions
|
the | mysql_connect | function can return a connection which is a data structure that wraps up a number of informations on the database and the user who connects to it; this data is to be handled by specifically designed functions -- the data type name is mysql link
|
the | mysql_query | function, when submitting a SELECT SQL statement, can return a table with rows and columns, which is to be handled by another set of functions -- the data type name is mysql result
|
These examples were seen in the foregoing chapter, in connection with database access applications.
The null data type represents data which have the value of null (case insensitive, i.e. NULL, Null, etc. are permissible representations). Such a data can be returned by some functions when they do not return the normal value (for example, the functions mysql_connect or mysql_query may return the null value when due to the argument value and the database state, they cannot run to normal completion).
Note that a variable that is not assigned a value is not NULL but undefined.
2.2.2 Data structures
The data types that are sometimes termed compound are really data structures composed of data of the different types described in the foregoing.
These data structures are:
- arrays
- objects
These structures which are not data but variables are described elsewhere (2.3.2 Array handling, 2.10 class and object).
2.2.3 Data type treatment
Data of any type and structure have a boolean value of (true or false) and a string value.
A scalar of any type: boolean, float, integer, string, can be used as one of any other type, i.e. a boolean or a string can be added to a number (but an object or an array cannot be used as a number).
The script below illustrates some of this. The data processed by the script are made to stand out in red, to distinguish them from the text to be merely printed out.
TestTreatment.php <?php
include "CircleFile.php";
if (new SampleCircle(15)) print ("<br>object='".new SampleCircle(15)."' is true");
if (array (1, 2, 3)) print ("<br>".array (1, 2, 3)." is true");
print ("<br>true=".true." - boolean true+2=".(true+2));
print ("<br>null=".null." - null+7=".(null+7));
print ("<br>".'12.34xyz56'." - string '12.34xyz567'+5=".('12.34xy56'+5));
?>
|
|
If you installed your Web server as suggested, please click here to run the script, the result of which is:
object being destroyed
object being destroyed
object='Object id #1' is true
Array is true
true=1 - boolean true+2=3
null= - null+7=7
12.34xy56 - string '12.34xy56'+5=17.34
|
The message 'object being destroyed' is emitted by the destructor of the object new SampleCircle. You see two of them at the beginning of the result display. The explanation is this:
1) | the two new SampleCircle(15) are two distinct objects
| 2) | each of these objects is destroyed as soon as it is created, because they are not saved into a variable; the second object has its value retained in the print function; the latter is completed after the object is destroyed
|
The string value of the object is "Object id #1".
|
The rest of the result shows this:
- | an object has the boolean value of true when it exists,
|
- | an array has the boolean value of true when it exists, and string value of 'Array'
|
- | a boolean has the integer value of 1 when true and 0 when false
|
- | a null has the integer value of 0
|
- | a string has as a numeric value the number, if any, found as the starting sequence of it
|
2.3.1 Variable names and data types
A variable name always starts with the $ sign. This is followed by a letter or an underscore, then any number of letters, digits and underscores. Example:
$_12x3Var_
A variable has no definite structure or data type. It takes on the latest structure and data type assigned to it.
TestVariable.php
<?php
include "CircleFile.php";
$a = Null; //NULL
if (!$a) print "\$a is NULL<br>";
$a = 123.45; //scalar - float
print ("\$a = $a<br>");
$a = array("a", "b", "c"); //array
for ($i=0; $i < count($a); $i++) {
print ("[$i] - $a[$i]<br>");
}
$a = new SampleCircle (20); //object
print ("radius=$a->rad");
$a = "xyz"; //scalar - string
print ("<br>\$a = $a<br>");
?>
|
The script on the left illustrates this. The variable $a is first assigned the value of null, then a scalar float, then an array, then an object, then a scalar string.
The object has a destructor which is called when the object is about to be destroyed. In the present case, it writes out the message 'object being destroyed'. This occurs when the object is replaced by the string as the variable value.
The count function returns the number of values contained in an array.
$a is NULL
$a = 123.45
[0] - a
[1] - b
[2] - c
radius=20
object being destroyed
$a = xyz
|
The script output is as shown on the right
If you installed your Web server as suggested, please click here to run the script and see this result
|
2.3.2 Arrays
An array is a data structure that contains a number of values, with each value mapped to a key.
An array value can be a data of any type and structure.
A key is either an integer or a string. When a string, a key is also called an associative key. An array can have both integer and associative keys. An array with associative keys is also called an associative array. Example:
TestArrayValues.php
<?php
include "CircleFile.php";
//data
$x = new SampleCircle (17);
$y = array ("t", "u", "v");
$z = "hatays";
//create array values
$a ['circle'] = $x;
$a [0] = $y;
$a [1] = $z;
//print array values
foreach ($a as $k=>$v){
print "$k => $v<br>";
}
print "<br>";
//print array items
$b = $a ['circle']; //object
print ("area=".$b->area()."<br>");
$b = $a [0]; //array
for ($i=0; $i < count ($b); $i++) {
print ("\$b[$i]=". $b[$i]."<br>");
}//end for
$b = $a[1]; //scalar
print ("\$a[1]=$b<br>");
?>
|
The script on the left creates an array $a and prints out its contents in different ways.
The data to be set as values into the $a array are:
- | an object of the class SimpleCircle, which is a circle the radius of which is set by the argument used to construct the object (17 in the example) -- this class has the area method which returns the circle area
| - | an array which contains the values "t", "u", "v" (with implicit keys 0, 1, 2)
| - | a scalar "hatays"
|
The script then first prints each of the values contained in the array, in the form:
key => value
The print function, in the form print datum prints out the string value of the datum:
- | the string value of an object is always in the form Object id #n
| - | the string value of an array is always Array
|
Then each of the values is retrieved from the $a array:
1- | the SampleCircle object which has the key 'circle' - the circle area as returned by the area method is printed
| 2- | the array which has the key 0 - each of its values "t", "u", "v" is printed
| 3- | the scalar "hatays" which has the key 1 is printed
|
|
circle => Object id #1
0 => Array
1 => hatays
area=907.92027585
$b[0]=1
$b[1]=2
$b[2]=3
$a[1]=hatays
object being destroyed
|
The script output is as shown on the left.
If you have set up your Web server as suggested, please click here to run the script.
The last line: object being destroyed is emitted by the destructor function of the SampleCircle object before the latter is destroyed (which occurs at script termination).
|
Array creation
There are different ways to create an array:
- by creating each of its items
- by creating it as a whole, using the array function
An array item can be created using the notation:
where:
array_name | is the name of the array
|
key | is the value of the key (enclosed within quotes if a string)
|
value | is the value to be assigned to the item
|
The key can be omitted (the contents of the square brackets is empty). It is then supposed to be an integer the value of which is the first unassigned value (starting at 0) in the script.
If the array did not exist, it is created.
An array can be created with multiple values, using the array function.
A simple example is:
$a = array ("x", 1, "y", "z"); |
The resulting array has the following key/value pairs:
key: 0 | value: "x"
|
key: 1 | value: 1
|
key: 2 | value: "y"
|
key: 3 | value: "z"
|
The keys are implied integers, varying from 0, by increments of 1.
The keys can be explicit. They must be explicitly stated to have a string value. Example:
$a = array (12, "name"=>"John", "surname" => "Blow", "age" => 32); |
The sign => is used between the key and its value.
The resulting array has the following key/value pairs:
key: 0 | value: 12
|
key: "name" | value: "John"
|
key: "surname" | value: "Blow"
|
key: "age" | value: 32
|
Array reference
Some of the properties of an array as a whole are:
- | any array has the string value of "Array"
|
- | the number of items in an array is returned by the count function.
|
An array item is referenced using the notation:
where:
array_name | is the name of the array
|
key_value | is the value of the key (enclosed within quotes if a string)
|
The key may be omitted (the contents of the square brackets is empty). It is then assumed to be numeric, with as a value the first integer value unassigned in the script.
Array functions
Arrays are handled by a number of array functions which are part of the core PHP. They are described elsewhere.
2.3.3 The scope of a variable
A variable defined in a script, outside any function, is accessible from anywhere in the script, except in the functions. Such a variable is a global variable.
From within a function, to access a global variable, you must declare it global, using the global keyword. Otherwise a variable used in a function is local to the function, even if it has the same name as a global variable.
<?php
$x = 3;
$y = 7;
$z = 5;
abacus();
calculus();
function abacus () {
global $u, $x, $y;
$u = $x + $y;
print "in abacus \$u=$u";
print $z;
}
function calculus () {
global $u;
print "in calculus \$u=$u";
}
?>
|
A variable declared in a function with the global keyword, but not outside a function is also a global variable, i.e. it is accessible from another function that declares it with a global keyword.
The script on the left illustrates all this.
The variables $x, $y, $z defined in the first lines of the script are global.
In the abacus function:
- | $u is a new global variable,
| - | $x and $y are the global variables defined earlier
| - | $z is a local variable, different from the $z global variable defined outside the function; as set here it is undefined, and trying to print it raises an exception
|
In the calculus function, $u is the global variable first defined in abacus
If you have set up your Web server as suggested, please click here to run the script.
|
A global variable is also accessible (outside the functions), from sequences copied into the script by an include statement, which is natural enough as included sequences are copied before the script is run, an the source of the code is then disregarded.
Another way to define a variable accessible from anywhere in the script is to set is as an item of the system array $_GLOBAL. In this case, the variable is readily accessible from within all of the functions, without the need of being declared 'global'.
2.3.4 Superglobal arrays
As a script is scheduled, informations from the client side and the PHP environment are made available to it in a number of system arrays called the superglobal arrays. These arrays are accessible from anywhere within the script.
CLIENT | HTTP communication | | | |
| USER | | name=value | PHP System |
| | | | | |
| | | | superglobals: | $_GET $_POST $_COOKIE
$_SERVER $_SESSION etc... |
| | | | | PHP script |
| | | | | |
|
|
The superglobal arrays and the informations they contain are:
- | informations contained in the user message:
$_GET | data read in from the HTTP message using the GET method
| $_POST | data read in from the HTTP message using the POST method
| $_COOKIE | cookies contained in the HTTP message
| $_FILES | identification of uploaded files
|
| - | informations from the environment
$_SERVER | client and server informations, contents of the HTTP message headers
| $_ENV | operating system environment informations
|
| - | informations from the session
$_SESSION | session informations
|
|
A PHP script is scheduled when a user sends in a message. The informations transmitted for processing by the message are made of a number of data in the form name=value. These data usually come from the INPUT elements of an HTML form the names and values of which give respectively the name and value components of the name=value pair. The PHP processor sets these data in the $_GET array if the method declared in the HTML form is GET, or in the $_POST array, if this method is POST. The keys and values in these superglobal arrays are respectively the names and values of the name=value pairs.
The $_COOKIE array contains the names and values of the cookies sent along with the message, with the cookie names as keys and the cookie values as values.
The $_FILES array contains the informations on the files uploaded by INPUT elements of the type file. The keys in the array are the names of the INPUT elements ("name" attributes). Each key maps to an array that points to the original name and the temporary file in the server that holds the uploaded file contents.
PHP$_FILES.html
<HTML><HEAD><TITLE>Test $_FILES</TITLE></HEAD>
<BODY>
<FORM action="PHP$_FILES.php" method="POST"
enctype="multipart/form-data">
<TABLE>
<TR><TD>Name:<TD><INPUT type="text" name="name">
<TR><TD>Surname:<TD><INPUT type="text" name="surname">
<TR><TD>email:<TD><INPUT type="text" name="email">
</TABLE>
<p>
<INPUT type="hidden" name="MAX_FILE_SIZE" value="32767">
File to upload:
<INPUT type="file" name="userfile" size="64">
<p>
Click here:
<INPUT type="submit" value="SUBMIT" name="button">
</FORM>
</BODY>
</HTML> |
The first script on the left (which is pure HTML) lets you select a file to upload to the server, then upon your clicking the SUBMIT, uploads the file and sends the request that calls the second script, with informations on the uploaded file.
If you have set up your Web server as suggested, by clicking on the PHP$_FILES.html name, above left, you run the script, and will be able to select a file to upload.
|
|
PHP$_FILES.php
<HTML><HEAD><TITLE>$_FILES</TITLE></HEAD>
<BODY>
<b>$_FILES contents</b><br>
Number of items in \$_FILES:
<?php
print(count($_FILES)."<br>");
print ("Key=Value pairs:<br>");
while (list ($ky, $val) = each ($_FILES)){
print ("$ky = $val<br>");
$lastval = $val;
}//end each
?>
<p><b>Contents of the array:</b><br>
<TABLE><TR><TD><b>Keys</b><TD><b>Values</b>
<?php
while (list ($key, $value) = each ($lastval)){
print ("<TR><TD>$key<TD>$value\n");
}//end foreach
?>
</TABLE>
<p><b>Uploaded file</b><br>
<?php
$handle = fopen($lastval['tmp_name'], 'r');
$n = 0;
while ((!feof($handle))&&($n < 20)){
$n++;
print (fgets($handle,512)."<br>");
if ($n > 20) break;
}
?>
</BODY></HTML>
|
The second script has 3 PHP sequences (in blue):
1 | the first sequence displays the keys and values of the $_FILES array. count($_FILES) is the number of key/value pairs contained in $_FILES. At each execution, each($_FILES) returns the next key/value pair. The list($ky, $val) statement on the left handside puts the key part into $ky, the value part into $val. Each key/value pair comes from an INPUT element with the file type:
. | the key is the name of the INPUT element that caused the upload
| . | the value is an array that holds the information on the uploaded file; when printed as a whole, it is displayed as 'Array'
|
The last (and only, here) array value ($lastvalue) is retained for future use.
| 2 | the second sequence prints out the contents of this array. Especially:
. | the key 'name' maps to the file name of the original file
| . | the key 'tmp_name' maps to the name of the file as uploaded in the server, which is a temporary file
|
| 3 | the third sequence prints out the first 20 lines of the uploaded file:
. | the fopen function opens the file identified by its URI, the second argument with the value 'r' indicates that the file is opened to be read. The function returns a handle to be used to designate the file.
| . | the feof function returns true when the End Of File has been reached in the file identified by its handle
| . | the fgets function returns the next line from the file, each line limited to 512 characters
|
|
|
keys | Signification
| name | source file name, at client siye
| type | file data type
| tmp_name | uploaded file name, at server site
| error | upload error code
| size | file size
|
The complete contents of an array item in $_FILES that describes each uploaded file is shown on the right.
You can see its contents for the file you uploaded if you run the script.
|
The $_SERVER array contains client and server data, along with the values of the headers contained in the received message.
PHP$_SERVER.php<HTML><HEAD><TITLE>$_SERVER</TITLE>
<STYLE>
TR {vertical-align:top;}
</STYLE>
</HEAD>
<BODY>
<b style="color:blue">$_SERVER superglobal</b>
<TABLE>
<TR><TD><b>Key</b><TD><b>Value</b>
<?php
while (list ($k, $v) = each ($_SERVER)) {
print ("<TR><TD>$k<TD>$v\n");
}
?>
</BODY></HTML>
|
The script on the left prints out the keys and the values of the $_SERVER array as currently exist in your computer.
Some of the keys are:
REQUEST_METHOD | method used to process the incoming message
| REQUEST_TIME | (available as of PHP 5.1.0) start of the request timestamp
| REMOTE_ADDR | the IP address of the requesting user
| REMOTE_HOST | the host name of the requesting user
| REMOTE_PORT | the port used by the host on the user side
|
The function list retrieves in each of its arguments the item of the same rank from the array returned by the function on the right handside. For each of the item in $_SERVER, the each function returns the key and the value, in this order. These are received in $k and $v respectively.
|
The keys you only see if security is in effect are:
PHP_AUTH_USER | user name provided by the user
|
PHP_AUTH_PW | password provided by the user
|
AUTH_TYPE | authentication type currently in effect
|
The $_ENV array contains informations on the operating system (Windows, UNIX, etc).
<HTML><HEAD><TITLE>$_ENV</TITLE></HEAD>
<BODY>
<TABLE border="1">
<TR><TD><b>Keys</b><TD><b>Values</b>
<?php
while (list ($key, $value) = each($_ENV)) {
print ("<TR><TD>$key<TD>$value\n");
}
?>
</TABLE>
</BODY></HTML>
|
The script on the left displays the keys and values of the $_ENV array as currently exist in your computer.
If you have set up your Web server as suggested, please click here to run the script, and see the keys and values contained in the $_ENV array.
|
While a user is connected to a Web server through an HTML page, she or he can link to another page, causing the new page to replace the current one. Through such links, the user can navigate among a number of pages. If these pages are used for the processing of the same problem, it may be necessary to retain certain informations across the changing of the pages. A session that persists during the whole problem procesing can be created for this purpose. The $_SESSION superglobal array is the structure where the data are retained for the session duration. The keys and values contained in the $_SESSION array are set by the user programs.
2.3.5 Static variables
A variable locally defined in a function can be declared static. It then retains its value across all the executions of the function. The declaration uses the static keyword:
where:
var_name | is the variable name
|
value | is the variable initial value -- optional (if omitted, the = is also to be omitted)
|
This declaration optionally sets the initial value of the variable, but is not executable so that the variable is not reset to its initial value each time the function in called.
TestStatic.php <?php
class SimpleClass {
public $count=0;
}//end SimpleClass
function foo (){
static $x=0, $arr, $obj;
$x++;
$arr[] = $x;
if (!isset($obj)){
print ("Creating SimpleClass object<br>");
$obj = new SimpleClass();
}
$obj->count++;
print ("\$x=$x ");
print ("count(\$arr)=".count($arr)." ");
print ("\$obj->count=".$obj->count."<br>");
}//end function foo
for ($i=0; $i < 3; $i++){
foo();
}
?>
|
The script on the left illustates the behaviour of static variables.
In the function foo the variables $x, $arr, $obj are declared static. The variable $x is given the initial value of 0.
Each time the function runs:
- | $x is incremented by 1
| - | a new item is added to $arr, which makes $arr an array
| - | if $obj was not defined (the function isset with $obj as an argument returns false), $obj is created as an instance of the SimpleClass (defined at the start of the script) -- a message is emitted signalling this
Then the property $count of the object is incremented by 1.
|
The function foo is called 3 times. The result is:
Creating SimpleClass object
$x=1 count($arr)=1 $obj->count=1
$x=2 count($arr)=2 $obj->count=2
$x=3 count($arr)=3 $obj->count=3
|
which shows the persistence of the static variables across the different calls.
|
|
If you have set up your Web server as suggested, please click here to run the script.
2.3.6 Variable reference
Assigning a variable by reference
In an ordinary assignment such as
$y takes on the value of $x, but the two variables are separate, a subsequent change to $x does not modify $y, nor a change to $y, $x. It is said that $x is assigned by value to $y: the value of $x is assigned to $y, but $x and $y are otherwise independent from each other.
An assignment can be made by reference, using the & sign:
(there can be a free white space between the & and the $ signs).
This assignment makes $x and $y two different names to identify the same datum. The two variables will have the same value: modifying $x will modify $y and vice versa.
TestReference.php <?php
class SimpleClass{
public $value = 0;
}//end class SimpleClass
$x = 6;
$y = & $x;
echo "y=$y "; // 6
$x = 7;
echo "y=$y "; // 7
$y = 8;
echo "x=$x<br>"; // 8
function foo ($x, $a, $o, &$y) {
$x = 17;
$a[1] = 17;
$o->value=17;
$y = 17;
}
$a = 0;
$arr = array (1, 2, 3);
$obj = new SimpleClass();
$b = 0;
foo ($a, $arr, $obj, $b);
print "\$a=$a<br>";
print "\$arr[1]=".$arr[1]."<br>";
print "\$obj->value=".$obj->value;
print "<br>\$b=$b";
?>
|
The script on the left first, shows a variable $x assigned by reference to a variable $y. The first echo result shows that $y has the same value, 6, as $x. Then $x is changed to 7. It is shown that $y also changes to 7. Now, $y is changed to 8 and $x is also changed to that value.
If you have set up your Web server as suggested, please click here to run the script.
Passing a variable by reference
Ordinarily, a variable is passed to a function by value, i.e. a copy of the variable is given to the function, and any operation performed by the function uses this copy, and does not affect the original variable.
However, alterations to a variable value brought about by the function can be made to reflect onto the original variable by passing the variable by reference. This is done by prepending the argument name with the & sign, in the definition of the function. The script on the left shows a function foo with the 3 first arguments passed by value, and last argument, $y passed by reference. The function modifies the value of these arguments.
The function is called and passed the 4 arguments to see how the original variables are affected. The result is shown below on the left:
y=6 y=7 x=8
$a=0
$arr[1]=2
$obj->value=17
$b=17
| The first 2 variables which are respectively a scalar and an array passed by value are unchanged. The third variable which is an object is seen to have changed: even though the argument does not have the & sign, it is passed by reference.
The fourth variable, passed by reference, is modified as expected.
|
The passing of a variable by reference when calling a function (e.g. foo(&$a,$arr,$obj,$b) with the function foo of the example) is now deprecated and will be altogether prohibited in future versions of PHP. The passing by reference must be defined in the function definition, as shown.
Reference to a function
A function can be declared to return the reference to a returned variable. This is done by prepending the & sign to the function name. Example:
function &function_name ( ...) {
global $a, $b, $c;
...
return $a;
}
$x = &function_name(...);
} |
In the script on the left, the variable $x is bound to the global variable $a returned by the function. An & must be prepended to the function name in the calling statement.
The returned variable ($a in the example) can be a scalar, an array or an object.
Also, the function must return one variable, not an expression.
|
Please click here to display a script that illustrates all this.
If you have set up your Web server as suggested, please click here to run the script.
Reference and the static and global properties
In a function, the global or static property of a variable is lost when the variable is assigned another variable by reference.
TestRefStatic.php <?php
class SimpleClass {
public $count=1;
}//end SimpleClass
function foo ($y) {
global $x;
static $obj;
if (!isset($obj)){
print "Create object<br>";
if ($y)$obj = &new SimpleClass(); //reference
else $obj = new SimpleClass(); //no ref.
}//end if isset
$x = $obj->count++; //increment after
}//end foo
print "ref:<br>";
for ($i=0; $i < 3; $i++){
foo(true);
print "$x <br>";
}//end for
print "<br>noref:<br>";
for ($i=0; $i < 3; $i++){
foo(false);
print "$x <br>";
}//end for
?>
|  
The script on the left shows the effect of an assignment by reference on the static property.
The variable used to illustrate the point is an object (but all that will be said holds true if it were a scalar or an array).
The function will create an object and assign it to the variable only if the latter was not set (if(!isset($obj)). The argument of the function ($y) is tested for its boolean value. When true, the variable is assigned the object by reference. When false, it is assigned by value.
Then the property variable 'count' of the object is incremented by 1, and assigned to the global variable $x.
ref:
Create object
1
Create object
1
Create object
1
noref:
Create object
1
2
3 |
The fonction is repeatedly called in 2 loops. In the first one, it is passed an argument of true so that the $obj variable is assigned the object by reference. In the second, the argument is false so that the object is assigned by value.
The result is shown on the right.
In the first loop where the variable is assigned by reference, it is discarded at the end of the function, so that the object is created and reassigned at each new call.
|
In the second loop where the variable is assigned by value, it is retained across the different calls, so that the object is created only once, and the property value of the object is incremented at each call to the function.
TestRefGlobal.php <?php
$x = 0; //global $x
$y = 1; //global $y
$z = 2; //global $z
function foo(){
global $x, $y, $z;
//local $x, $y, $z bound to globals
$y = &$x; //local $y bound to global $x
$z = &$x; //local $z bound to global $x
$y = 3; //also global $x = 3
}//end foo
foo ();
print ("x=$x y=$y z=$z");
?> |
A global declaration binds the declared local variables to the global variables of the same names, i.e. the local variables now identifies the same data as the global variables.
In the function foo on the left, the global declaration binds the local variables $x, $y, $z to the global variables of these names.
Then $x is assigned by reference to $y and $z: this binds the local variables $y and $z to the global variable $x. This is demonstrated by assigning the value of 3 to $y then displaying the (global) variables $x, $y and $z in the main sequence:
- | $x now has the value of 3 that was assigned to $y in the function.
| - | the global variables $y and $z are unchanged since they were disconnected from their local counter parts when these were bound to global $x
|
Reference insight
When a variable $x is assigned by reference to a variable $y, these variables are bound together; by this it is meant that they both identify the same datum. This can be represented by the figure on the left.
The value can be changed through either of the variables $x or $y; it remains the value common to both.
|
The unset function can be used to deprive a variable of its value. The variable becomes unset. This means that the link between its name and its former value is broken.
When 2 variables are bound together, unsetting one of the variables does not unset the other, as shown in the figure on the left.
|
Constants can be given a name in a PHP script.
2.4.1 Constant values
A named constant can have as value a scalar datum (integer, float, boolean or string). Arrays and can not be used as values of named constants.
2.4.2 Constant names
The name that designate a constant conforms to the same rules as that of a variable:
- | the first character is a letter or an underscore
| - | the rest is made of letters, underscores and numbers in any number and order
| - | in addition to the characters in the ranges [a-z] and [A-Z], characters with codes ranging from x7F to xFF are also considered letters
|
There is no $ before the name of a constant.
By convention, it is advisable that letters in a constant name be uppercase.
Names starting with 2 underscores are to be avoided, because they are used by PHP.
2.4.3 Constant definition
A constant is defined by the define function, using the syntax:
define ("constant_name", constant_value |
where:
constant_name | is the name to be assigned to the constant -- this name is enclosed within quotes
| constant_value | is the value assigned to the constant; this can be an integer, a float, a boolean or a string (within quotes if a string)
|
Example:
define ("PI", 3.14159265) |
2.4.4 Constant visibility
A constant is visible from anywhere in a script, including from inside a function.
2.4.5 Some constant functions
Some of the functions related to constants are:
- constant
- get_defined_constants
ConstantList.php
<?php
define ("MY_CONSTANT", "Hatay");
$x = "MY_CONSTANT";
print "constant=".constant($x);
$a = get_defined_constants();
print "<p>There are ".count($a);
print " pre-defined constants:<p>";
foreach ($a as $k => $v) {
print ("$k => $v<br>");
}
?>
|
The constant function returns the value of a constant when the constant name, or more interestingly, a variable containing the name of a constant is passed to it.
The get_defined_constants function returns the list of all the constants currently defined, in the PHP core, by the extensions, or by the user. This list is an array with the constant names as the keys and the constant values as the values.
The script on the left shows the usage of these functions.
|
2.5.1 Operator description
Operators might be categorized as:
- | Scalar operators that operate on scalar data. These include:
. | arithmetic operators that result in arithmetic values
| . | boolean operators that result in boolean values
| . | string operators that result in string values
|
| - | Bitwise operators that operate on data bits
| - | Array operators that operate on arrays
| - | Class operators that deal with classes and objects
| - | Assignment operators
| - | Control operators
|
Scalar operators
The scalar operators are presented in the tables below.
Arithmetic operators
+ | Addition
| - | Subtraction
| * | Multiplication
| / | Division
| % | Modulo
| ++ | Increment
| -- | Decrement
|
The addition, subtraction, multiplication, division are the 4 well known operators that need not be elaborated upon. The modulo operator divides the term to the left by the one to the right and retains the remainder as the result. All these are binary operators that operate on 2 operands.
The increment and decrement operators are unary operators, that operate on a single operand, which must be a variable. The increment operator add 1 to the value of the variable. The decrement operator subtract 1 from the value of the variable.
|
Different notations using these operators are:
++$x | increment before
| $x++ | increment after
| --$x | decrement before
| $x-- | decrement after
|
When the variable is involved in another operation, the before notation causes the increment/decrement to occur before the other operation is performed, the after notation causes the increment/decrement to occur after. Example:
print ++$x | $x is incremented before the print operation occurs
| print $x-- | $x is decremented after the print operation occurs
|
There are 2 categories of boolean operators:
- comparison operators
- logical operators
Comparison operators
A comparison operator has 2 operands. The result is a boolean datum which has the value of true or false
== | equal
| === | identical
| != | not equal
| <> | not equal
| !== | not identical
| < | less than
| <= | less than or equal
| >= | greater than
| > | greater than or equal
|
TestComparison.php <?php
$a = 1;
$b = "1xyz";
if ($a == $b) print "\$a is equal to \$b<br>";
else print "\$a NOT equal to \$b<br>";
if ($a === $b) print "\$a is identical to \$b";
else print "\$a NOT identical to \$b";
?> |
Two variables are identical if they are equal and of the same data type. The script on the right shows the distinction between equal and identical. The variables $a and $b both have the numeric value of 1, but one is of the integer type and the other is a string, so they are equal, but not identical.
If you have set up your Web server as suggested, please click here to run the script.
|
Logical operators
and | AND | $x and $y is true if both $x and $y are true
| && | AND | $x && $y is true if both $x and $y are true
| or | OR | $x or $y is true if either $x or $y is true
| || | OR | $x || $y is true if either $x or $y is true
| xor | exclusive OR | $x xor $y is true if either $x or $y is true, but not both
| ! | NOT | !$x is true if $x is false
|
There are two AND operators, and and &&. They operate the same way on their operands, but do not have the same precedence with regard to the other operators. Similarly there are two OR operators or and ||.
|
String operators
$a . $b results in a string made of $a followed by $b.
|
The increment operator can operate on a string of letters and figures. Capital letters vary from A to Z, then to A and 1 is carried over to the character on the left; if there is no character to the left, an A is generated. Lower case letters behave similarly. Figures vary from 0 to 9, then to 0 and 1 is carried over to the character on the left; if there is no character to the left, a 1 is generated.
TestCharIncrement.php <?php
$a = "ABC";
print ++$a."<br>"; ?>
<BR>
<?php
$b = "abz";
print ++$b."<br>"; ?>
<BR>
<?php
$c = "Zz8";
for ($i=0; $i < 10; $i++) {
print $c++."<br>";
} ?>
<BR>
<?php
$d = "9Y";
for ($i=0; $i < 10; $i++) {
print $d++."<br>";
}
?>
|
The script on the left illustrates these incrementing rules.
Incrementing "ABC" results in "ABD".
Incrementing "abz" results in "aca": z is changed to a with an increment carried over to b which becomes c.
Incrementing "Zz8" results in "Zz9", then "AAa0, etc...
The lasr example has a figure as the leftmost character. Incrementing "9Y" results in "9Z", then "10A", etc...
If you have set up your Web server as suggested, please click here to run the script.
|
Bitwise operators
The operators operate on the values of the variables to produce a result. The original variables are unchanged. In the table below two variables $x and $y are used as examples; the operators can operate directly on values.
$x & $y | bitwise AND | a bit is 1 if the bit in its position is 1 in both operands
| $x | $y | bitwise OR | a bit is 1 if the bit in its position is 1 in either or both operands
| $x ^ $y | bitwise exclusive-OR | a bit is 1 if the bit in its position is 1 in one of the operands but not in both
| ~ $x | bitwise NOT | unary operator: in the value from variable $x, 1 is changed to 0 and 0 to 1, bitwise
| $x << $y | shift left | the bits from variable $x are shifted $y positions to the left -- vacated positions filled with 0
| $x >> $y | shift right | the bits from variable $x are shifted $y positions to the right -- vacated positions filled with 0
|
|
The bitwise operators are intended for 32-bits integers. However, the AND, OR and exclusive-OR can be used when both operands are strings.
Array operators
Array operators
+ | union
| == | equal
| === | identical
| != | not equal
| <> | not equal
| !== | not identical
| The union operator uses the values of the two array operands, and does not affect the arrays themselves. It appends the items from the second operand to the value of the first, ignoring the items from the second operand which have a key already present in the first. This means that if a key is present in both arrays, in the resulting array, the value mapped to the key is that from the first array.
Two arrays are equal if they have the same set of key/value pairs. Two key/value pairs are the same if the two keys are identical and the two values are equal.
Two arrays are identical if they have the same set of key/value pairs in the same order.
|
TestArrayUnion.php<?php
$a = array ("name" => "Fanny", "surname"=>"Adams");
$b = array ("name" => "John", "surname"=>"Blogg",
"email"=>"jblogg@hatays.com");
$c = $a + $b;
foreach ($c as $k => $v){
print ("$k => $v<br>");
}
?>
|
In the script on the left, both the $a and $b arrays have the keys name and surname. The $b array has the additional key email. In the union $a + $b the item email=>jblogg@hatays.com from $b is added to the 2 items from $a
If you have set up your Web server as suggested, please click here to run the script.
|
Class operators
new | instanciates a class
| instanceof | tests the class of an object
|
|
The new operator instantiates a class, i.e. creates an object of it. It used with the following syntax is:
$object = new class_name (arguments) |
where:
object | is the name of the variable to hold the created object
| class_name | is the name of the class to instantiate
| arguments | represents the arguments required by the class constructor
|
The instanceof operator determines whether a variable is an instanceof a designated class. It is used with the following syntax:
$var instanceof class_name |
where:
var | is the name of the variable
| class_name | is the name of the class
|
The result is true is the variable is an instance of the class.
Assignment operators
$y = $x assigns the value of $x to $y
|
The expression $x = value has a value which is the value assigned to $x. For example, $x = 17 has the value of 17. This can be used in a statement such as:
if ($var = function_xxx(...)) { ... } |
which assigns the value returned by the function to a variable, and steers different courses of action depending on the function outcome.
The ordinary assignment is by value. Assignment can be done by reference by putting a & sign before the name of the variable in the right handside:
The right hand side must be a single variable or function, or a new operation, not an expression nor a value.
|
An operator can be put to the left of the = sign.
Control operators
@ | error control
| ` ... ` | backquotes operator : executes a command string
|
|
When prepended to the function name, in a function call, the @ operator suppresses any error message from the function. You can replace it by a message of your own:
$var = @ myFunction()
or print ("myFunction terminated in error"); |
Example:
TestErrorControl.php <?php
$var = @ file("non_existent") or
print "<b>file</b> function failed";
print "<br>This is why:<br>";
print $php_errormsg;
?>
|
The script on the left illustrates the use of the @ error control operator. As the file function fails, the second term of the or operation is evaluated; this evaluation causes the print function to be called. The @ operator prevents the script from being terminated. Here it goes on to print out the contents of the system variable $php_errormsg, which holds the last error message generated. This is the message that the @ operator prevented from being displayed. For the variable $php_errormsg to be defined, the option track_errors must be set to on, in the PHP initialization file (php.ini).
|
If you have set up your Web server as suggested, please click here to run the script.
The backquotes (``) operator executes the shell command comprised within the backquotes (a shell command is a command executed by the operating system, Unix or Windows). Executing a shell command using the bacquotes operator is prohibited when the PHP safe mode is on (this is controlled by the safe_mode directive in the PHP initialization file -- php.ini). In the safe mode, shell command executing is performed through the shell_exec( ) function.
Conditional operator
(condition) ? (value_when_true) : (value_when_false) |
|
|
The ? ... : is a ternary operator which involves 3 operands, noted in the above as:
condition | the condition to be tested
| value_when_true | value to use when the condition is true
| value_when_false | value to use when the condition is false
|
The whole expression has a value determined by the condition that makes up the first component -- the value is:
- | the expression on the left of the : sign (value_when_true) if the condition is true
| - | the expression on the right of the : sign (value_when_false) if the condition is false
|
Example:
$min = ($a < $b) ? $a : $b |
2.5.2 Precedence
When more than one operator are present in an expression, the operators are applied in the order determined by their precedences. Precedence is an intrinsic property attached to an operator. For example, the * (multiply) operator has a higher precedence than + (addition), so that, in the expression:
1 + 2 * 3
the * operator is applied first, and the expression value is 7.
A table giving the precedences among the operators is given in the reference manual.
In this, you can see that the numeric and string operators have higher precedences than the comparison operators, which means that the former are applied first, before comparisons are made.
Also, the && AND and || operators are applied before any assignment, whereas the and AND and or OR are applied after the assignments. For example:
- | $a and $b = $c or $d | is equivalent to $a and ($b=$c) or $d
| - | $a && $b = $c || $d | is equivalent to ($a && $b) = ($c || $d)
|
2.5.3 Associativity
Among the operators of the same precedence, the order of application depends on their associativity.
An operator can be left- or right-associative. When left-associative, the operations are carried out from left to right, with at each step the last obtained result combined with the next operand on the right (unary operators cannot be associative). When right-associative, the operations are carried out from right to left, with the last result combined with the next operand on the left.
The preference table in the reference manual also gives the associativity property of the operators.
According to the Reference Manual "almost anything you write is an expression. The simplest, yet most accurate way to define expression is 'anything that has a value'".
An expression has a data type and a basic value as a data of its data type. Besides:
- | all data have a string value and a boolean value
| - | scalar data have a value when used as a data of any other scalar type (e.g. a boolean has an integer value).
|
2.6.1 What an expression is
An expression can be:
- one constant,
- one variable,
- one function call,
- a string of constants, variables, functions connected by operators.
- etc...
2.6.2 Expression data type and value
The trivial cases are expressions that combine data of the same type: integer, float or string, they are of the data type of their components. Examples:
|
$a = 1;
$b = 2;
$c = 12.3;
$d = 45.67;
$e = "abc";
$f = "def";
$x = $a + 12 * $b - 3;
$y = $c - $d / 4.3;
$z = $e . $f . "ghi"; |
In the example on the left:
- | $x and the expression on the right handside are of the integer type
| - | $y and the expression on the right handside are of the float type
| - | $z and the expression on the right handside are of the string type
|
An expression where integers are mixed with floats or the result of which is not an integer has the float type.
|
An expression where 2 scalar data are combined by a comparison operator is of the boolean type.
An expression that includes the assignment operator (=) has the type and value of the assigned data.
<?php
$a = 17;
$b = 4;
$c = "some string";
print "\$a=$a<br>\$b=$b<br>\$c=\"$c\"";
print "<br>\$a < \$b: ";
var_dump ($a < $b);
print ("<br>\$x = \$a/\$b: ");
var_dump ($x = $a / $b);
print "<br>\$x = \$a: ";
var_dump ($x = $a);
print ("<br>\$x=$x");
print ('<br>$c."10other" +$a: ');
var_dump ($c . "10other" + $a);
print "<br>\$a < \$b + 20: ";
var_dump ($a < $b + 20);
print "<br>(\$a < \$b) + 20: ";
var_dump (($a < $b) + 20);
?>
|
The function var_dump can be used to display the type and value of an expression.
Some illustrations of this is demonstrated by the script on the left.
$a=17
$b=4
$c="some string"
$a < $b: bool(false)
$x = $a/$b: float(4.25)
$x = $a: int(17)
$x=17
$c."10other" +$a: int(17)
$a < $b + 20: bool(true)
($a < $b) + 20: int(20)
|
The result of the script is shown on the right. On each resulting line, the expression (in red) is displayed on the left of the colon (: sign), and its type and value as returned by the var_dump function (in blue) is shown on the right:
- | expression $a < $b is a boolean with the value false
|
- | expression $x = $a/$b is a float with the value 4.25
|
- | expression $x = $a is an integer with the value 17
|
- | expression $c."10other"+$a is an integer with the value 17: due to left associativity, the concatenation $c."10other" that comes first, is performed first, then the string "string10other" is used as a number and added to $a
| |
- | expression $a < $b + 20 is a boolean with value true: due to operator precedence, $b+20 is performed first, then the operation $a < 23 is performed, resulting in the boolean value true
| - | expression ($a < $b) + 20 is an integer: ($a < $b) is a boolean with the value false, its numeric value of 0 is added to 20
|
|
2.6.3 More on expression evaluation
Where arithmetic or string operators are involved, the evaluation of an expression is straightforward and conform to common knowledge. The evaluation of an expression containing the assignment (=) operator may need some illustration.
One of the very commonly used expressions is of the form:
$var = some_function (arguments)
or die ("error_message"); |
where the die function is called to print out the message denoted "error_message
", and terminate the
script if, and only if, the function some_function abnormally terminates, or more precisely, returns a null value. The function die is not called if some_function runs successfully and returns a normal value (which must not be null or 0, or more generally something that is interpreted as a boolean false).
In the script below, the function file is called with the operator @ that suppresses the error message. The habitual function die is replaced by print which prints out the message "file function failed ".
TestOR.php <?php
// or OR
$var = @file("non_existent")
or print "file function failed";
print "<br>This is why:<br>";
print $php_errormsg;
if (isset($var)) print "<br>\$var is set";
else print "<br>\$var is not set";
if (is_null($var))print "<br>\$var is null";
else print "<br>\$var's value is ";
var_dump($var); ?>
<P>
<?php
// || OR
$var = @file("non_existent")
|| print "file function failed";
print "<br>This is why:<br>";
print $php_errormsg;
print "<br>\$var's value is ";
var_dump($var);
?>
The script output is shown below on the right.
|
The function file is called twice, with a bad argument to make it fail. The first time it is connected to the function print by the operator or, the second time by the operator || which is an alternative form for or.
As or has a lower precedence than =, in the expression that calls the function the first component to be evaluated is:
$var = @file ("non_existent")
If the file function fails, it returns the value null, and this expression is false; otherwise, it returns true, and the expression is true.
Then the or operator is applied to evaluate the whole expression: $var = @file ("non_existent") or print "file function failed"
- | if its first term (to the left of the or operator) is true (the file function completed successfully), the whole expression is true and the evaluation is terminated, the second term print ( ... ) need not be and is not evaluated, i.e. the print function is not called.
| - | if the first term is null (the file function failed), the second terms needs to be evaluated, and print is called.
|
|
file function failed
This is why:
failed to open stream: No such file or directory
$var is set
$var's value is bool(false)
file function failed
This is why:
failed to open stream: No such file or directory
$var's value is bool(true)
|
After the file function is called, the $php_errormsg variable is printed out. It is a PHP variable that contains the most recent message from the system (the track_errors directive in the php.ini file must be on). Presently, it is the error message from the file function that was suppressed by the @ operator.
Then the function isset tests whether the $var variable is set. As it turns out, it is.
The function is_null tests whether the $var variable is null. It is not: as the var_dump function shows it, it has the boolean value of false
If you have set up your Web server as suggested, please click here to run the script.
The second call to the file function uses the || form of OR. It produces the result slightly from the first, as it works differently.
As the || operator has a higher preference than =, in the expression that calls the file function the || operator is applied first to evaluate the expression:
@file("non_existent") | | print "file function failed"
- | if the file function is successful, it returns true and the expression is true, the second term (to the right of ||) need not be and is not evaluated, i.e. print is not called
| - | if the function fails, it returns false and the second term needs to be evaluated, i.e. the function print is called.
|
The assignment operator = is next applied, i.e. the value of the expression on the right handside, evaluated as just said, is assigned to the variable $var.
After the function call, the error message from the $php_errormsg variable is written out.
This time, the variable $var has the value true, which is the value returned by the print function.
|
PHP has statements to control the execution flow of a script. These are essentially:
- the if statement
- the switch statement
- the while statement
- the do ... while statement
- the foreach statement
- the for statement
Ancillary statements not presented here are described in the Syntax Summary
2.7.1 The if statement
In its simplest form, the if statement causes a set of statements to be executed if a certain condition is true:
if (condition) {
statement-set
} |
where:
condition | is the condition to be tested for its boolean value
| statement-set | is the set of statements executed if the condition is true
|
|
The condition tested in the if statement can be any type of expression, since data of any type and structure all have a boolean value. Example:
if ($ok = mysql_query("CREATE DATABASE myDatabase")) {
print ("MyDatabase successfully created!");
} |
In the example, the expression that makes up the condition is:
$ok = mysql_query ("CREATE DATABASE myDatabase")
It has the boolean value of the result returned by the function mysql_query. At the same time, this value is assigned to the variable $ok
The statement set is made of the lines enclosed between the curly braces. In the example, the statement set consists of one line, but in the general case, the number of lines is unlimited.
In its complete form, the statement has:
- | one required if clause
|
- | optional elseif clauses in any number
|
- | one optional else clause terminating the statement
|
For example:
. . .
$info = getdate($date);
$mon = info ("mon"); //month 1-12
$yday = info ("yday"); //day in year
$wday = info ("wday"); //day of week
if (($mon > 6)&&($mon < 9)) {
print "Summer period<br>";
print "very busy";
}
elseif (($yday > 30)&&($yday<36)){
print "Winter sports<br>";
print "peak period";
}
elseif (($wday==0)||($wday==6)){
print "Weekend<br>";
print "busy";
}
else {
print "normal activity";
}
|
In this example, if the condition ($mon > 6)&&($mon < 9) is met, the statements print "Summer period<br>"; print "very busy"; are executed. Otherwise:
- | if the condition ($yday > 30)&&($yday<36) is met, the statements print "Winter sports<br>"; and print "peak period"; are executed.
| - | if the condition ($wday==0)||($wday==36) is met, and none of the above are, the statements print "Weekend<br>"; and print "busy"; are executed.
|
If none of the conditions are met, the statement print "normal activity"; is executed.
The if statement is composed of a number of clauses introduced by one of the keys word: if, elseif, else. The clauses are in the order: if, elseif, ..., else. Each clause specifies a condition within parentheses, and a set of associated statements enclosed within curly braces. The conditions are examined in the order they appear. As soon as a condition is found to be true, the associated set of statements is executed, and the if statement terminates. If none of the conditions is true, the statements associated with the else clause are executed, if such a clause is defined.
|
The formal syntax is described in the Syntax summary.
2.7.2 The switch statement
The switch statement provides for the selection of a set of statements to execute, based on the value of a key. Example:
TestSwitch.php<?php
if (!isset($_GET ["lingua"])) {
?>
<FORM action="TestSwitch.php"
method="GET">
Please enter a language :
<INPUT type="text" name="lingua">
<BUTTON type="submit" name="sub">
GO
</BUTTON>
</FORM>
<?php
}//end if isset
else {
$language = $_GET["lingua"];
define ("ENGLISH", "english");
define ("FRENCH", "french");
define ("GERMAN", "german");
define ("ITALIAN", "italian");
define ("NOENTRY","");
switch ($language) {
case NOENTRY :
print "Entree VIDE<BR>";
case FRENCH :
$table = FRENCH;
print "Bonjour !";
break;
case GERMAN :
$table = GERMAN;
print "Guten Tag";
break;
case ITALIAN :
$table = ITALIAN;
print "Buongiorno !";
break;
case ENGLISH :
default:
$table = ENGLISH;
print "Hello!";
}//end switch
}//end else is_null
?>
|
This is a complete script which contains the code to display a communication box for you to enter a choice, then to execute a sequence that implements the switch statement to select the statement set that suits your choice. The single script is used for both stages.
Determining which stage the script is in is handled by the if statement (in red):
- | the first time the script is called, the $_GET superglobal array is empty (has no item set); the function isset applied to $_GET["lingua"] returns false. In this case, the <FORM> element that defines the communication box is generated onto the result HTML page. This FORM which has the attribute action="TestSwitch.php" will cause the script to be called back when the SUBMIT button is clicked
| - | the second time, the script is called by your clicking on the submit button of the FORM, with the data you entered registered in the "lingua" item of the $_GET array; the sequence that processes this information is executed.
|
This sequence gets your choice into the $language variable, and defines a number of constants: "ENGLISH", "FRENCH", etc., just to stress the fact that the word coded to the right of the keyword case must represent a constant (you can just code case "english", etc...)
The statement starts with the switch keyword and an expression within parentheses ($language in the example). This is followed by a number of case clauses starting with:
where case is a keyword and constant a constant. |
This notation is generally followed by a statement set. But there can be no statement set, as after case ENGLISH.
At execution time, the statement is scanned top-down, when a constant in a case clause equals the specified expression, the statements found after the colon (:) of the case clause are executed. The execution goes on until a break statement or the end of the statement is encountered. Example: when $language is an empty string, the statement 'print "Entree VIDE<BR>"' is executed, then the execution carries on to the statements '$table=FRENCH' and 'print "Bonjour !"'
|
The default clause comes last, when present. Its statement set is excuted when none of the constants is equal to the specified expression.
2.7.3 The while statement
The while statement repeatedly executes a set of statements as long as a given condition is true. Such a condition is an expression which generally is modified by the statement set, or by itself. The condition is tested before each run.
Example:
while ($row = mysql_fetch_array ($result)){
print ("<BR>); //presentation row
$i = 0;
while ($i < $col) {
print "<TD>$row [$i++] </TD>";
}//end while $i
}//end while $row
|
In this example, there are 2 embedded while loops.
In the outer statement, the condition is $row = mysql_fetch_array($result) which has the same value as $row, and has a boolean value of true as long as mysql_fetch_array returns a non-null result. The condition is an expression which modifies itself. If it is true, the statements contained in the curly braces that follow are executed. After a run, the condition is tested again for a new run.
|
In the inner statement, the condition is $i < $col. This condition is m:odified by the statement contained in the loop ($i++).
A formal description of the statement is to be found in the Syntax summary.
2.7.4 The do ... while statement
The do ... while statement executes a set of statements, and repeats the execution as long as a given condition is true. Such a condition is an expression which generally is modified by the statement set, or by itself. The condition is tested after each run; if true, a new run is started.
Example:
TestDoWhile.php
<?php
$arr = array (3, 5, 7, 4, 2, 1);
$i = 0;
$x = $arr[$i];
$s = $x;
print ("\$x=$x \$s=$s<br>");
do {
$b [] = $x;
$x = $arr[++$i];
$s += $x;
print ("\$x=$x \$s=$s<br>");
}
while ($s < 16);
print ("count = ".count($b));
?>
|
The do statement first executes the statement set contained within the curly braces. It then tests the specified condition $s < 16. If true, a new run of the statement set is carried out. After each run, the test is repeated for a new run. The statement is terminated when the tested condition is false.
In this example, the condition is modified in the statement set.
If you have set up your Web server as suggested, please click here to run the script.
|
2.7.5 The foreach statement
The foreach statement extracts successive keys and values from an array, and for each extracted key/value pair, executes a set of statements. It works only with arrays. Using any other data structure will give rise to an error.
TestForeach.php
<?php
$arr["name"] = "John";
$arr["surname"] = "Dory";
$arr["email"] = "jdory@piscinia";
$arr["phone"] = "1-877-1236457";
foreach ($arr as $kk => $val) {
print "key: $kk - value: $val<br>\n";
}
?>
|
The script on the left creates an array $arr, then uses the foreach statement to extract successive key/value to be processed by the statements within the curly braces. The key is retrieved into the $kk variable, the value into $val.
The foreach statement here is in its full form which makes the key and the value of each key/value pair available for processing. Its simple form where only the value is available would be (only $val is available for use):
foreach ($arr as $val) { ... }; |
|
If you have set up your Web server as suggested, please click here to run the script.
2.7.6 The for statement
The for statement:
- executes a set of initial statements
- repeatedly executes a loop composed with
. a condition to be tested
. a body made of statements to be executed if the foregoing condition is true
. a set of sequence ending statements executed after the loop body
The statement ends when the condition is false
SampleFor.php
<?php
if (count($_GET)==0){
?>
<FORM action="SampleFor.php" method="GET">
<TABLE>
<TR><TD>Database name:
<TD><INPUT type="text" name="dbase">
<TR><TD>User name:
<TD><INPUT type="text" name="user">
<TR><TD>Password:
<TD><INPUT type="text" name="pass">
<TR><TD>Table name:
<TD><INPUT type="text" name="table">
<TR><TD>
<TD><INPUT type="submit" name="button"
value="SUBMIT">
</TABLE>
</FORM>
<?php
}//end if count
else {
?>
<b>Table description</b><br>
<STYLE>
TABLE {background:red;}
TD {background:white;padding:0.25em;}
</STYLE>
<TABLE>
<TR><TD>Field<TD>Type<TD>Null
<TD>Key<TD>Default<TD>Extra
<?php
$host = "localhost:3306";
$user = $_GET['user'];
$pass = $_GET['pass'];
$link = mysql_connect($host,$user,$pass)
or die ("Unable to connect");
for (mysql_select_db($_GET['dbase']),
$desc = mysql_query("DESC ".$_GET['table']),
$col = mysql_num_fields($desc)
;
$row = mysql_fetch_array($desc)
;
print "\n")
{
print ("<TR>");
for ($i=0; $i < $col; $i++) {
print ("<TD>$row[$i]");
}//end for $i
}//end for $row = mysql_fetch_array
}//end else
?>
</TABLE>
</BODY></HTML>
|
To the left is a script that generates a form for you to enter a database, user name and password and a table name, then uses a complex form of the for statement to display the description of the table.
The if statement (in red), tests the stage in which the script is:
- | when the script is first called, the $_GET array is empty, the number of items returned by the count function is 0, which is interpreted as false; the data entry FORM is then generated for you to enter the desired data
| - | when the script is next called, the $_GET array contains the data sent in from the entry FORM; the script then processes these data.
|
To process the data, the HTML code for the beginning of the table where the result will be presented is generated, outside the PHP sequence. The PHP sequence first creates a connection to the database server (function mysql_connect).
Then, its executes a for statement which has another for statement embedded.
In the outer for statement, the control part enclosed within the parentheses which follow the for keyword has the following components:
1) | the initial sequence composed of 3 statements which retrieves the table description and column number into the $desc resource and $col scalar variables; these statements are separated by a comma
| 2) | the condition made of the expression $row = mysql_fetch_array($desc) which retrieves a description row into the $row array, and is true as long as the $desc resource has a row to return; after all rows have been returned, the expression is false and the for statement is terminated.
| 3) | the loop ending statement set which consists of the single statement print "\n";.
|
These 3 components are separated by a semi-colon.
The loop body is the set of statements contained within the outer curly braces.
The inner for statement is simpler:
- | the initial set is made of the single statement $i = 0
| - | the condition is $i < $col which terminates the statement when the index $i reaches the value $col
| - | the loop ending statement is $i++ which increments by 1 the value of the index after each loop
|
|
This is just an example to show how complex an initial set of statements can be. In a real application, you might not set all of the statements used here in this set, because not all statements are accepted there. Particularly, the or and similar operators, and the if, for, while and other control statements are not allowable in the initial statement set, so that you cannot handle the cases when the functions fail.
If you have set up your Web server as suggested, please click here to run the script. You need to have created a database, a user with its password and a table. How to do this was shown in the Introduction chapter.
2.7.7 Other statements
The description of the other control statements is to be found in the Syntax summary section.
2.8.1 Function definition and function call
Functions can be defined in a script for calling from different locations.
A function is defined using the syntax:
function function_name (argument_list)
{
function_body
} |
where:
function_name | is the name you assign to the function
|
argument_list | is the comma separated list of arguments passed to the function
|
function_body | is the set of statements executed when the function is called
|
A function is called by stating its name, followed by the list of arguments enclosed within parentheses:
function_name (argument_list) |
When a function is defined with an empty list of arguments, the parentheses are still required, with nothing or white space between them, when the function is called.
The argument names specified in the function represent the data to be coded in their positions at call time. If a function is defined as function xyz ($a, ...) and called as xyz (datum, ...), then the operations in the function body where $a is present, use the value of datum in place of $a for that call.
Ordinarily, a call to a function can be made anywhere in a script, before or after the function is defined. Only when the function definition is dependent on the execution of some part of the script, is it required that calls to it occur after its definition (see infra).
2.8.2 Argument passing by value vs by reference
Passing an argument by value or by reference was already discussed earlier in this chapter. here is a reminder.
When a variable appears merely with its name in the argument list, it is passed by value to the function. When a variable name in the argument list is preceded by the & sign, it is passed by reference.
When a variable is passed by value, the corresponding argument is a copy of it. Modifying the argument in the function only modifies the copy, not the original variable itself. When the variable is passed by reference, the corresponding argument represents the original variable itself, so that modifying the argument will modify the original variable.
All this is true with scalar and array data type arguments. Object type arguments are always passed by reference.
2.8.3 Argument default value
Default values can be assign to arguments so that you need not enter them at call time. For example:
TestDefaultArg.php function foo ($a, $b=12, $c=22) {
print "\$a=$a \$b=$b \$c=$c";
}
foo (11,33); |
This would print | $a=11 $b=33 $c=22 |
Note that when an argument is omitted in a function call, all of the arguments to its right, if any, must be omitted. With the function foo as defined above, a call like foo (11, , 33) is incorrect.
2.8.4 Returned value
A function can be made to return a value so that the latter it can be assigned to a variable. The return statement is used to return a value. It terminates the execution of the function.
If a function terminates without returning a value, assigning it to variable would leave the variable unset.
Example:
TestReturn.php
<?php
if (!count($_GET)) { ?>
<FORM action="TestReturn.php">
Enter a value <INPUT name="in">
<BUTTON type="submit" name="sub">
OK</BUTTON>
</FORM>
<?php
}//end if
else {
function foo($a){
if ($a) return 1234;
$a = "anything";
}//end function
$x = foo($_GET["in"]);
if (isset($x)) {
print "\$x is set ";
if(is_null($x))print "\$x=null";
else print "\$x=$x";
}
else print "\$x is not set";
if ($x) print " \$x is true";
else print " \$x is false";
}//end else !count ($_GET)
?>
|
In the script on the left, the function returns the value '1234' if it is called with an argument which has the boolean value true. Otherwise, it terminates without returning a value.
The first part of the script generates an HTML form to let you enter a value. After you submit the value by clicking the OK button, the script is called back and its second part is executed. It calls the function and passes it the value you entered: $x=foo($_GET["in"])
You can either enter a value, or click the OK button without entering a value. In the first case, the function returns the value '1234' which is assigned to $x. In the second case, it returns nothing and $x is not set -- this is different from being set with a null value, but the boolean value is false anyway.
If you have set up your Web server as suggested, please click here to run the script.
|
Only one value can be returned. The returned value can be a scalar, an array or an object.
To return multiple values (e.g. multiple arrays, or a mix of scalars, arrays and objects), you have to put them in an array, and return the array.
The returned value can be retrieved into an array. You can also directly retrieve each of the array item into a variable, using the list function like this:
list ($x, $y, $z) = foo (...); |
$x, $y, $z are assigned the returned array items with indices 0, 1 and 2. Therefore, in the function, the array has to have integer indices. Example:
TestList.php
<?php
class Sample {
public $value = 17;
}//end class
function foo ( ) {
$a = "someString";
$b = array (1, 2, 3);
$c = new Sample ();
$arr[] = $a;
$arr[] = $b;
$arr[] = $c;
return $arr;
}//end function foo
list ($x, $y, $z) = foo ();
print "\$x=$x<br>$y=$y<br>$z=$z<br>";
foreach ($y as $key=>$val) {
print "key=$key val=$val<br>";
}//end foreach
print "object=>value $z->value";
?>
|
The function foo creates 3 variable:
- $a, a scalar,
- $b, an array,
- $c, an object
and puts them into the array $arr. As in $arr[] the index value is blank, successive integer values 0, 1 and 2 are assumed.
When calling foo using the list function, the items in the returned array are put in the variables $x, $y and $z, by increasing order of the index. The result is printed for checking.
$x=someString
$y=Array
$z=Object id #1
key=0 val=1
key=1 val=2
key=2 val=3
object=>value 17
|
This result is shown on the right
Note that as a whole:
- | an array has the string value of Array
| - | an object has the string value of Object id #n
|
If you have set up your Web server as suggested, please click here to run the script.
|
2.8.5 Dependent definition
A function can be defined in a set that is executed conditionally, such as an if, elseif or else clause, of a case clause in a switch statement, or it can be defined in another function. In these cases, the function is defined only after the set is executed. Therefore:
- | any reference to the function can occur only after the location where the function is defined
|
- | such a reference is valid only if the set where the definition is, is executed
|
TestDependent.php
<?php
if (!count($_GET)) { ?>
<FORM action="TestDependent.php">
Enter a value <INPUT name="in">
<BUTTON type="submit" name="sub">
GO</BUTTON>
</FORM>
<?php
}//end if
else {
//foo() - call to foo is erroneous here
if ($_GET['in']) {
//boo() - call to boo erroneous here
function foo (){ //--------------------
//$a = "from foo: ".boo(); wrong here
function boo( ){
return $_GET['in'];
}//end boo
$a = "from foo-".boo(); //OK here
return $a;
}//end foo -----------------------------
print "foo is defined, so is boo<br>";
}//end if $_GET
else {
print "foo NOT defined<br>";
}//end else $_GET
$x = foo();
print ("foo=$x ");
$y = boo ();
print "boo=$y";
}//end else count
?>
|
The first part of the script generates an entry form for you to enter a data. The second part processes the data so entered. In this, 2 function are defined:
- | foo which is in the set executed if $_GET['in'] is true.
| - | boo which is defined in the body of foo
|
foo can be called only after the if ($_GET['in']) statement. And the call is successful only if $_GET['in'] is true.
boo can be called only after foo is called. And the call is successful only if foo is executed successfully.
If you have set up your Web server as suggested, please click here to run the script.
You can type some characters in the data entry field, then click the GO button. These characters are trensmitted to the $_GET['in'] item, which then has theboolean value of true. Then foo is defined, and is executed successfully, and so is boo
You can click the GO button without entering any thing into the data field. The item $_GET['in'] is then empty, an has the boolean value of false. The statement set containing the definition of foo is not execute. foo is not defined. So the call to foo fails. boo is not defined.
|
2.8.6 Including user function libraries
A function can be useful in more than one script. Such a function can be defined in a separate file. The scripts that use the functions of this file can include it using an include statement. The include statement must occur before any reference to a function contained in it.
FileFunction.php <?php
print "FileFunction included";
print "<br>\n";
function foo () {
return 10;
}
function boo ($a) {
return $a;
}
?>
| On the left is the contents of the file FileFunction.php to be included in the script below. Note that its PHP code must be enclosed within PHP tags, the <?php and ?> tags, here.
|
TestInclude.php
<?php
print "Test include<br>";
include "FileFunction.php";
$x = foo();
print "\$x=$x";
?>
| This is the script that includes the above file, using the include statement. A reference to a function defined in the file can occur only after the inlude statement.
|
The directory where the included file is to be set depends on the include_path PHP configuration directive. You can have a directive like this:
In Unix:
include_path = ".:/php/includes"
In Windows:
include_path = ".;c:/php/includes"
|
The "." represents the current directory, i.e. the directory where the script is. This allows you to set files in the same directory as the scripts, for including. The other directory is includes, contained in php which is usually the home directory of your PHP system.
Please run the PHPInfo.php script from the samplesdirectory, and look for the include_path value to find out where the include directories of your PHP system are. You can put your include files there. Any (reasonable) number of directories can be defined in the value of the include_path parameter.
|
Alternatively (this is the only possible course if the include_path directive is not set), you can put your include files in the same directory as the scripts.
2.8.7 PHP functions
The PHP environment offers a great number of functions. Their detailed description can be found in the Reference Manual
These functions fall into 2 catagories:
- the functions of the PHP core modules
- the functions brought in by the extension modules
The core modules are built into the PHP package. They are available without your having to do anything.
The extension modules must be declared in the PHP initialization file (php.ini). They are in the form of .dll files to be loaded in the ext PHP directory. Many of them are readily loaded there when you install the standard distributed PHP package. As of PHP 5, some others are to be fetched from the PECL (PHP Extension Community Library) package. Others still have to be imported from independent vendor sources. All must be named in the php.ini file through the extension directive.
The Reference Manual describes the modules, core or extension, in the Function Reference chapter, and for each of them, gives the following informations:
- | the initialization directives that control the behaviour of operations related to the module (Runtime configuration)
|
- | the resource type that can be returned by some of the functions of the module (Resource Types).
|
- | the named constants defined by the module (Predefined constants). Each of these constants has a value, but you need not know it. It is recommended to designate a constant by its name, because an unchanging signification is guaranteed to be attached to a name, whereas the value may change.
|
- | the functions offered by the module; a list of them is presented in the table of contents of the module, which has a link to the complete description of the function.
|
Some of the function from the PHP core are described in the following.
WARNING With most of the PHP functions, arguments are passed by value. Therefore, a variable passed to a function for processing is not modified. In the following, sometime is it said for briefness sake, that a passed variable is modified in such and such manner, it is then meant that its value is so modified; the modification is not reflected back onto the original variable. The final result of these functions is what they return.
2.9.1 String functions
The string functions carry out most of the operations on string data. Only concatenation is done by an operator (the . operator).
The other string operations are handled by these functions (details in the Syntax summary):
- | presentation functions -- send a string for display to the user, or set it in some format for later displaying:
. | printing (print, printf, echo)
| . | formatting (number_format, money_format, fprintf)
| . | hexadecimal form (bin2hex)
|
|
- | search and replace functions -- locate, return or replace a substring matching a description, within the processed string
. | search (strpos, strrpos)
| . | search and return substring (substr, strrchr, strstr, strrpos, strpbrk, strtok)
| . | replace (str_replace)
|
|
- | analysis functions -- return the length of the string or the portion of the string free of undesired characters, the number of words of a certain description, or the words themselves
. | lengths (strlen, strcspn)
| . | counting (str_word_count, substr_count)
| . | retrieving words, key/value pairs as from URLs (parse_str, str_word_count, explode)
| . | splitting into small chunks (str_splitting)
|
|
- | construction function -- constructs a string from the items of an array
. | collating from arrays (implode)
|
|
- | comparison functions -- compare two strings or their substrings, taking case into account or not
. | total strings (strcmp)
| . | substrings (strncmp, substr_compare)
|
|
- | transformation functions -- trim or pad a string on both ends, insert or remove escaping backslashes, convert characters
. | trimming and padding (trim, str_pad)
| . | backslashes handling (addslashes, stripslashes
| . | character conversion (strlolower, strtoupper, strtr, ucfirst, ucword)
| . | reverse character order (strrev)
|
|
- | HTML page handling -- encode and decode character references, add/remove <BR> tags
. | entity handling (htmlentities, html_entity_decode)
| . | <BR> tags (nl2br, striptags)
|
|
- | etc...
|
2.9.2 Date and time functions
The date and time functions return date and time information in the forms of:
- | a timestamp which is a number of seconds or microseconds elapsed since a certain origin -- a popular timestamp is the UNIX timestamp which takes as origin the 1st of January, 1970, at 00 o'clock, 00 minute, 00 second, 000000 microsecond.
|
- | some formatted presentation
|
Some of these functions are:
- | time returns the UNIX local timestamp (time elapsed since January 1st, 1970, 00:00:00 GMT), in seconds
|
- | date returns the specified components (hour, minute, second, year, day, month, etc...) of the current local time, or of the time as defined by a timestamp -- example :
date ("Y, M d -- H:i:S") returns a date like 2005, Jan 31 -- 19:12:25
|
- | gmdate same as date but the time is GMT
|
- | getdate returns the components of the current local time, or a given timestamp, in an associative array with key names: "seconds", "minutes", "hours", "mday", "month, "year", etc..
|
- | microtime returns the current local timestamp in seconds and microseconds
|
TestTime.php
<?php
$t = time();
print "time()=$t<br>";
print "microtime()=".microtime()."<br>";
print "date()=".date ("Y, M d -- H:i:s", $t)."<br>";
print "gmdate()=".gmdate ("Y, M d -- H:i:s")."<br>";
$timearray=getdate();
print "getdate():<br>";
foreach ($timearray as $kk=>$val) {
print ("- $kk = $val<br>");
}
?>
|
The script on the left illustrates these functions. In the date and gmdate functions, the argument "Y, M d -- H:i:S" describes the time components to be returned:
Y | represents the year in full 4 digits,
| M | represents the month in abbreviated 3-letter form,
| d | represents the day in the month,
| H | represents the hour from 00 to 23,
| i | represents the minute from 00 to 59,
| S | represents the second from 00 to 59.
|
The other characters , -- : are printed 'as is'.
|
More on these functions is to be found in the Syntax Summary.
2.9.3 Array functions
The array functions provide for:
- | Array creation:
. | specifying a list of key/value pairs (array)
| . | from a list of variables (compact)
| . | merging two or more arrays (array_merge)
|
|
- | Array summary: number of items (count), value total (array_sum)
|
- | Keys and values extraction:
. | extracting into variables (list, extract)
| . | extracting the keys or values into an array (array_keys, array_values)
|
|
- | Searching for a value (array_search)
|
- | Handling an array as a stack (array_pop, array_push, array_shift, array_unshift)
|
- | Sorting (asort, ksort)
|
- | Walking through the array:
. | moving the current pointer(next, prev, reset, end)
| . | retrieving the current key and value pair (each), or the current key alone (key)
|
|
- | etc...
|
TestArrayFunc.php
<?php
$arr = array ('Jack','Pot','jpot@free.us');
list ($name, $surname, $email) = $arr;
print "$name $surname $email";
print "<P>";
$brr = compact("name", "surname", 'email');
foreach ($brr as $kk=>$v){
print "key=$kk val=$v<br>";
}
print "<br>";
reset ($brr);
while ($a = each ($brr)) {
$x = extract ($a);
//$x = extract ($a, EXTR_PREFIX_INVALID, "p");
print "$x variable extracted ";
print ("\$key=$key \$value=$value<BR>");
} //end while
print "<br>";
$crr = array ("name", "surname");
$e = "email";
$drr = compact($crr,$e);
foreach ($drr as $kk=>$v){
print "drr - key=$kk val=$v<br>";
}
?>
|
The script first creates an array $arr, then retrieves the values of the array into the variables $name, $surname and $email, using the list function. The $arr array has integer indices, as required.
Then the array $brr is created from the retrieved variables, using the compact function. Note that the names of the variables, 'name', 'surname' and 'email' are within quotes, and no $ sign is present.
The keys and values of the $brr array are retrieved and printed in a foreach loop. After this, the current position in $brr has to be reset to the start of the array, using the reset function. This makes the first key/value pair 'current'.
The each function extracts the current key/value pair from an array, and returns it in an array with 4 keys named '0', 'key', 1' and 'value', where: the keys '0' and 'key' are mapped on to the name of the extracted key, and the keys '1' and 'value' onto the extracted value.
Thus, as the first key/value pair from $brr is 'name/Jack', the first result retrieved in $a is an array with the keys '0' and 'key' mapped onto the value 'name', and the keys '1' and 'value' onto the value 'Jack'.
From this first array, the function extract extracts the variables $key='name' and $value='Jack' which are printed in the while loop. The pairs 0/name and 1/Jack do not result in any variable, because 0 and 1 are not valid as variable names. The function extract returns the number of extracted variables, which is 2.
An alternative form of the call to extract, which is commented out, uses the arguments EXTR_PREFIX_INVALID and "p" which would prefix the key names 0 and 1 which are invalid as variable names, with the prefix 'p', changing them into p0 and p1. The extract function would then extract the variables $p0='name' and $p1='Jack' in addition to the $key and $value variables.
The last call to the compact function passes it 2 variables which contain the names of the variables to be compacted into an array. You see how these variables ($crr and $e) appear in the arguments.
|
More on these functions is to be found in the Syntax Summary.
2.9.4 File system functions
The file system functions handle the operations with conventional data files and their environment. See also $_FILES for a related topic.
The common operations with a file are about writing to and reading from it. They may involve its opening and closing.
Other operations described in this document involve:
- | querying the file properties such as their size or their base and directory names
|
- | handling the environment: creating and removing directories, renaming, copying, determining the type of a file
|
- | handling file security data
|
The simplest way to read from a file is probably to get the whole of it into a string in one operation. This is done by the function file_get_contents, as shown in the script below:
TestFileGet.php
<?php
print "file_get_contents<p>";
$uri = "../samples/files/Alice.html";
$size = filesize($uri);
print "File size: $size<p>";
$buff = file_get_contents($uri);
print "File contents:<br>";
print "$buff";
?>
|
The file is identified by its URI. In the example, this URI is the relative path to the file, from the directory where the script is located.
The filesize function can be called to return the size of the file, i.e. the number of bytes it contains.
The function file_get_contents returns the entire file as a string.
|
In the above example, the file is in the local host. The function can access a remote host, when the allow_url_fopen directive in the php.ini PHP intialization file is on. The script below illustrates this:
TestRemoteGet.php
<?php
print "file_get_contents<br>";
$uri = "http://hatayservices.com/HATAYIndex.html";
$buff = file_get_contents($uri);
print "$buff";
?>
|
The file HATAYIndex.html exists in our site hatayservices.com. But the site may not be found, if you are not connected to the communication network. To have a wire or a wireless physical connection is not to be connected yet. You have to establish the logical connection. The easiest is to connect to your e-mail server, as if to read your e-mail. The file_get_contents function will use the telephone connection you estalished.
|
Similarly the file_put_contents writes a string as a bulk to a file. If the file did not exist, it is created. This is illustrated by the example below.
TestFilePut.php
<?php
print "file_put_contents<p>";
$uri = "../samples/files/Alice.html";
$buff = file_get_contents($uri);
$uri = "../samples/files/Croquet.html";
$n = file_put_contents($uri, $buff);
if (file_exists($uri)) print "File size=$n";
else print "File NOT created";
?>
|
The contents of file Alice.html is read into the string $buff, then written out to a file named Croquet.html. When successful, the function file_put_contents returns the number of the written bytes.
The function file_exists tests for the existence of the file to be created. If the file was created, the number of its byte is written out
|
In the example, only 2 arguments were used with file_put_contents. In this case, if the file already existed, its old contents are erased and replaced by the new string. To add the new data behind the existing contents, you use a third argument with the value FILE_APPEND:
file_put_contents (file_uri, data_string, FILE_APPEND) |
The function file_put_contents does not support writing to a file accessed through a http protocol (even if it is http://localhost...). Anyway, a host is usually protected against the writing to it from a remote user.
The functions file_get_contents and file_put_contents need no prior opening of the file. Other functions require the file to be opened before they can process it.
A file is opened through a fopen function, which locates the physical file. The syntax in a simple form with 2 arguments is:
where:
file_uri | is the URI of the file. This URI can identify
- | a local file, when it is the file local path
| - | a remote file, such as located by a URI of the form http://host_and_port/file_path; this is possible only if the PHP initialization directive allow_url_fopen is set to on
|
|
mode | is the mode of operation for which the file is opened. This argument can have a value such as:
r | open the file for read only
| r+ | open the file for read and write, the file pointer is placed at the start of the file (the file pointer is where the next read or write starts).
| w | open the file for write only, erasing the old contents -- file created if it did not exist
| w+ | open the file for write and read, erasing the old contents -- file created if it did not exist
| a | open the file for appending: old contents is preserved, file pointer placed at end of file
| a+ | open the file for appending and reading -- file created if it did not exist
|
The description of all the possible values of this argument can be found in the Syntax Summary
|
The function returns a special resource called handle. This is to be received in a variable to be passed as an argument to certain of the file processing functions.
An opened file is closed by the fclose function. The syntax of the latter is:
where file_handle is the handle previously returned by an fopen function. The fclose function is not always needed, as files are automatically closed when the script which opened them terminates.
The script below shows some of the functions that use the file handle.
TestFopen.php
<?php
$uri = "../samples/files/Alice.html";
print "\n<p>Opening file<br>\n";
$alice = fopen ($uri,'r');
$i =0;
while ($line = fgets ($alice)) {
print $i++."- ";
print "$line<br>";
}//end while
print "<p>fseek (rewind) and fread<p>";
$size = filesize ($uri);
print "size=$size<br>";
$n = fseek($alice, 0);
//rewind ($alice);
$text = fread ($alice, $size);
print "$text";
fclose ($alice);
?>
|
The physical file Alice.html is a local file identified by its relative path. The fopen function returns the file handle into the variable $alice.
The fgets identifies the file by its handle. At each calls, it returns the next line from the file. After all the file is read, it returns a null value. In the while loop, each line is printed, with its number displayed at the beginning.
After the file is read through, the file pointer has to be reset at the beginning of the file. This is done by the fseek the second argument of which (0 here) is the byte position where the file pointer is to be set. An equivalent function for setting the pointer to 0 is rewind.
The function fread returns the number of bytes from the file, as specified by its second argument, starting at the current file pointer position.
|
The function fwrite writes out a number of bytes limited to a specified value, starting at the current file pointer position.
These functions can be used to handle the so-called direct access files. These files hold their data in chunks of constant length that can be called records. These records are identified by their rank in the file, which is a number that can start at 0. As the record length is known, the rank of a record determines its position in the file. The fseek can be used to set the file pointer to the desired position to read or write the record starting at that position.
The script below illustrates the use of the fseek, fwrite and fread functions.
TestDirectAcc.php
<?php
$arr = array ("alpha", "beta", "gamma", "delta");
foreach ($arr as $k => $v) {
print "$k=>$v ";
}
$uri = "../samples/files/Direct.txt";
$len = 7;
$handle = fopen ($uri, 'w+');
print "<br>";
for ($i = 0, $pos=0;
$i < count($arr);
$pos +=$len) {
fseek ($handle, $pos);
print ("i=$i position=");
print (ftell($handle)."<br>");
fwrite ($handle, $arr[$i++], $len);
}//end for
$n = 2;
$pos = $n * $len;
$x = fseek ($handle, $pos);
$val = fread ($handle, $len);
print "$val";
?>
|
The script first creates the array $arr which contains the values 'alpha', 'beta', 'gamma' and 'delta', and checks it.
The file 'Direct.txt' is then opened for write and read (mode w+). The values contained in the $arr array will be written out to this file, in chunks of 7 bytes long.
This is done in a for loop. The variable $len contains the length of the chunks (7). It is used as the third argument of the fwrite function. This argument sets the maximum length to be written. The file pointer does not advance by 7 at each fwrite, but by the amount really written. The new position of file pointer after each fwrite has to be explicitly defined by the variable $pos which is incremented by 7 at the end of each loop.
This position is set in the file by the fseek function. The function ftell returns the current value of this position, just for checking purpose.
The last sequence retrieves a record that has the number 2 (3rd record in the file), and displays it.
|
TestFile.php
<?php
$uri = "../samples/files/Alice.html";
print "URI=$uri<br>";
print "Directory path: ".dirname($uri)."<br>";
print "File name: ".basename($uri)."<br>";
print "Absolute path: ".realpath($uri)."<br>";
$uri = "http://localhost/hpp/files/Alice.html";
print "<p>URI=$uri<br>";
print "Directory path: ".dirname($uri)."<br>";
$a = realpath ($uri);
print "realpath returned a ".gettype($a);
if (!$a) print "- FALSE";
?>
|
File management includes functions for returning the file name proper, i.e. the right most component of a path (function basename), or the directory path (function dirname) from a file URI.
For local files, the function realpath returns the absolute path. For files located through the http protocol, realpath returns the boolean false (the getttype returns the data type of the argument).
The script on the left illustrates these functions.
|
Other file management functions include functions that test if a given URI identifies a file (function is_file) or a directory (function is_dir), or other properties of a file such as, whether it readable (function is_readable), writable (function is_writable), executable (function is_executable), an uploaded file (function is_uploaded_file), etc.
The file system environment is managed through functions such as:
rename | changes the path name of a file; this can move a file to another directory if the new path identifies a directory different from the old
|
copy | copies a file onto the same or a different directory, assigning it a new path name; the origin file can be remote, the destination must be local.
|
unlink | deletes a file
|
mkdir | creates a directory
|
rmdit | deletes adirectory
|
2.9.5 Variable functions
The variable functions report on, or otherwise process a variable as such (Reference).
The functions print_r and var_dump are particularly useful in displaying the type and value of a variable.
The function serialize returns a string representation of a variable, which can be transmitted over a communication link, or recorded in a data file or a database. This applies especially to array, object or resource variables. The function unserialize rebuilds a serialized variable to its original form.
Other functions which show the status of a variable are:
isset | returns true if the variable has been assigned a value. A variable is not set, for instance, if is is assigned a value in a conditional sequence that was not executed. A variable also is not set when assigned a function which does not return a value. A variable can also be put in the 'not set' status by the unset function (in this case, it is deprived of its previously existing value). When 'not set' a variable cannot be tested by an operator (such as if) or a function other than isset.
is_null | returns true if the variable has the value null. Note that being null is different from being 'not set'; this is also different from having the value of an empty string. However, in both latter cases the variable is considered false when tested e.g. by an if statement.
| gettype | returns the type of data currently contained in a variable
| is_array | returns true if the variable has the array structure. Other similar functions are is_bool, is_float, is_int, is_numeric, is_object, is_resource, etc...
| floatval | returns the float value of a variable
| intval | returns the integer value of a variable
| strval | returns the string value of a variable
| |
The example below shows how serializing and unserializing works with an object. The procedure applies to arrays or resources as well.
|
TestSerialize.php
<?php
include "ClassesSample.txt";
$rec = new Rectangle (10, 20);
$serial = serialize ($rec);
$uri = "../samples/work/rectangle.obj";
if (file_put_contents($uri, $serial)) {
print "rectangle.obj file created";
}
print "<p>print_r:<br>";
print_r ($rec);
print "<p>var_dump:<br>";
var_dump ($rec);
$val = file_get_contents ($uri);
$obj = unserialize ($val);
$area = $obj->area();
print "<p>area=$area";
?>
The script on the left creates an object of the class Rectangle (shown below), then serializes it using the serialize function and writes out the resulting string to the rectangle.obj file.
In passing, the functions print_r and var_dump are called to display the informations on the $rec object.
Finally, the string representation of the $rec object is read into the $val string from the rectangle.obj data file. The unserialize is called to restore the object to its original value. The area method of the restored object is called, proving that the restored result is the original Rectangle object.
| ClassesSample.txt
<?php
class Rectangle {
private $width = 0;
private $length = 0;
function __construct ($x, $y) {
$this -> width = $x;
$this -> length = $y;
}//end construct
public function area (){
return $this->width * $this->length;
}//end area
public function dimension(){
$a[] = $this->width;
$a[] = $this->length;
return $a;
}//end dimension
}//end class Rectangle
?>
| On the left is the specification of the Rectangle class. It is contained in the ClassesSample.txt file.
This class has 2 properties, width and length which represent the width and length of the Rectangle object. These properties are not directly accessible from outside the class, because they have the private property.
The constructor (function __contruct as recommended), records the object width and length values as specified at creation time.
Two functions are defined, area which returns the rectangle area, and dimension which return the width and length values in an array.
| TestUnserialize.php
<?php
include "ClassesSample.txt";
$uri = "../samples/work/rectangle.obj";
$val = file_get_contents ($uri);
$obj = unserialize ($val);
list ($wid, $len) = $obj->dimension();
print "Rectangle $wid x $len <br>";
$area = $obj->area();
print "area=$area<br>";
if (unlink ($uri)) print "Object file deleted";
else print "Unlink unsuccessful";
?>
| The TestSerialize.php script did read in the string object representation from a file and
unserialize it, to show how an object can be restored from its file record. The TestUnserialize.php script on the left, more decisively proves the point by processing the record in an independent script.
To unserialize an object, the class of the object must be defined in the script. Here the class description is obtained by the include operator.
The unserialize function restores the object into the $obj variable.
The dimension method of the object returns the width and length values of the restored object in an array. The list function retrieves the contents of the returned array into to the variables $wid and $len which are printed for checking.
|
|
Finally the script deletes the file containing the object by calling the unlink function.
2.9.6 PHP options and informations
These functions return information on the PHP environment. Some of them provide for setting the options of the currently running PHP system. (Reference).
Best known is the function phpinfo which displays the general information about the current PHP system, and the configuration options of the PHP core and the functional extensions.
The function ini_set allows you to set certain configuration directives to a value which will be in force during the script life time. In the reference manual there is a list of directives with their changeability properties. Only the directives marked as PHP_INI_USER or PHP_INI_ALL can be changed by the ini_set function. The function returns the directive old value when successfully executed, the false value otherwise. The function ini_get returns the current value of a configuration directive.
The function set_time_limit sets the maximum execution time, in seconds, of the current script (default: 30 seconds).
MySQLTrace.php
<?php
if (!count($_GET)) {
?>
<FORM action="MySQLTrace.php"
onsubmit="if (data.value=='') {
location.replace('TheEnd.html')
return false
}
else return true">
Trace MySQL (YES/NO)?:
<INPUT type="text" name="data">
<BUTTON type="submit" value="sub">
GO</BUTTON>
</FORM>
<?php
}//end if
else {
if (strcasecmp($_GET['data'],"YES")==0) $trace="on";
else $trace = "off";
$r = ini_set ("mysql.trace_mode", $trace);
echo "MySQL trace now ".ini_get("mysql.trace_mode");
}
?>
|
The script sends to the user a data entry box, when it is first called. When it is called back it tests the data received in the $_GET superglobal array, with the key 'data' (which is the name of the INPUT field where the data come from).
If the data is "YES", the ini_set function is called, to set the MySQL option mysql.trace_mode to the value on. Else, it is set to off.
The comparison between $_GET['data'] and YES uses the function strcasecmp which compares two arguments, disregarding case (strcmp is the case sensitive comparison). The function returns 0 when the arguments are equal.
After the ini_set function, ini_get is called to show the new status of the option mysql.trace_mode.
|
All of the function in this category are described in the reference manual. Here is the link, again.
2.9.7 Miscellaneous functions
Categorized under the miscellaneous heading are a number of important functions. Some of them are illustrated here. A complete description is to be found in the Reference Manual.
The eval function
The eval function returns the value of the expression constituted by the argument. The result is as though the expression was hard coded into the script. For example:
The operations indicated by $a + $b - $c is performed, and the result is assigned to $x.
|
This yields the same result as though the following line were hard coded in the script:
But using the eval function, the operations can be made variable. For example:
$str = "$a";
if ($cond) $str +="+$b"; //$str = "$a+$b"
else $str += " - $e"; //$str = "$a-$e
$str += "-$c"; //$str = "$a+$b-$c" or "$a-$e-$c"
$x = eval ($str);
|
Depending on a condition $cond, the expression to evaluate is different.
The function is thus seen to provide for determining by program the operations to carry out.
|
Script execution control
Script execution control is provided for by the following functions:
exit | terminates the current script and displays a status or a message
|
die | an alias for exit
|
sleep | delays further processing for a number of seconds
|
usleep | delays further processing for a number of microseconds
|
time_nanosleep | delays further processing for a number of seconds and nanoseconds
|
The die (or equivalently exit) function is often used to terminate a script in case of some function failure. Example:
mysql_select_db($dbase)
or die ("Unable to open database $dbase");
|
The function die, when executed, displays the message "Unable to open database $dbase" and terminates the script.
Constant handling
The function define defines a constant, assigning it a name. The function defined returns true if its argument has been defined as the name of a constant. The function constant returns the value of a constant; the constant name can be directly passed as an argument of the function, or it can be contained in a variable passed to the function. Example:
TestConstant.php
<?php
$name = "SORT_NUMERIC";
echo "$name has the value ".constant($name);
?>
|
SORT_NUMERIC is a predefined constant.
|
Pack and unpack
The pack and unpack functions are about changing the representation of numbers to and from an extended and a compact form.
A number as represented in a program code, is a string of digits, each of which represented by an octet of bits i.e. a 2-digit hexadecimal number. Thus: the decimal digits from 0 to 9 are represented by the hexadecimal numbers from '30' to '39'. Hexadecimal digits beyond 9 are coded as letters from 'A' (or 'a') to 'F' (or 'f'), represented by the hexadecimal numbers from '41' to '46' (resp. from '61 to '66'). Thus, the 6-digit hexadecimal number "123AbC" is represented by this sequence of 6 octets:
This is the extended form of representation for a number.
The pack function changes the extended form of representation into a more compact one. Its syntax is
where:
mode | is the mode of transformation
|
number | is the number (or sequence of digits) to process
|
The most widely used forms, perhaps, are with the mode values of "H" or "h". In the result, the figures from '0' to '9' and from 'A' to 'F', are represented by hexadecimal numbers from 0 to 9 and A to F, and packed, two into one octet. The number "123AbC" is then represented by this sequence of 3 octets (the distinction between upper and lower case is irrelevent here):
in mode "H", this is the so-called 'high nibble first' or 'big-endian' byte representation
|
or this:
in mode "h", this is the so-called 'low nibble first' or 'little-endian' byte representation
|
Some of the other packing modes are:
c | a number from 0 to 255 results is an octet containing the binary value of the number
|
n | a number from 0 to 65535 results in 2 octets containing the binary value of the number, with the higher order octet first
|
v | a number from 0 to 65535 results in 2 octets containing the binary value of the number, with the lower order octet first
|
s | a number from 0 to 65535 results in 2 octets containing the binary value of the number, the position of the lower and and higher order octets is machine dependant
|
i | a number from 0 to 429497296 results in 4 octets containing the binary value of the number, the ordering of the octets is machine dependant
|
In the example below, the bin2hex function is used to show the hexadecimal representation of the result strings, so that you see the hexadecimal contents of each of their characters.
TestPack.php
<?php
$a = "123ABC";
$x = pack("H5", $a);
$y = pack("h*", $a);
echo "pack H 123ABC = ";
echo bin2hex($x);
echo "<br>pack h 123ABC = ";
echo bin2hex($y);
print "<p>\npack c 65, 10, 255 = ";
echo bin2hex(pack('c*',65,10,255));
echo "<p>\npack n 512 = ";
echo bin2hex(pack('n',512));
echo "<br>pack v 513, 1024 = ";
echo bin2hex(pack('v2',513, 1024));
echo "<br>pack v 65530 = ";
echo bin2hex(pack('v',65530));
echo "<p>\npack i 65538 = ";
echo bin2hex(pack('i',65538));
?>
|
pack H 123ABC = 123ab0
pack h 123ABC = 21a3cb
pack c 65, 10, 255 = 410aff
pack n 512 = 0200
pack v 513, 1024 = 01020004
pack v 65530 = faff
pack i 65538 = 02000100
|
The results are shown on the right.
The 2 first calls use the packing modes "H" and "h".
The 5 to the left of H indicates the number of digits to be processed, from the original number. As 2 digits go in each resulting octet, the fifth one is alone, so that in the result, the nibble to its right is 0.
The * sign to the left of h indicates that all of the digits in original sequence (there are 6 of them here) are to be processed.
The third call to the function uses the mode c; the * indicates that all of the arguments that follow are to be processed. There are 3 of them here. Each of the number is transformed into one octet: 65 is transformed into its hexadecimal value 41, 10 into 0a, and 255 into ff.
|
|
In the 'n' mode, a short integer (number from 0 to 65535) is transformed into its 2-octet binary representation. In the example, the n standing alone means 'transform one argument'. The number '512 is transformed into the hexadecimal number 0200.
The v mode, like n, transforms short integers. But in the result, the octet of lower order comes first. The number 513 the hexadecimal representation of which is 0201, is represented in the 2-octet result as 0102. The number 1024 which has the hexadecimal value 0400 is represented as 0004. The number 65530 which has the hexadecimal value fffa is represented as faff.
The last example shows the effect of the i mode which transforms an integer into its 4-octet representation.
The example below shows an implementation of the pack function with more than one packing mode:
TestPackMore.php
<?php
echo "pack H3nc* 456,897,12,13 = ";
echo bin2hex(pack('H3nc*',456,987,12,13));
?>
with the result:
pack H3nc* 456,897,12,13 = 456003db0c0d
|
Here:
- | the H mode applies to 3 digits of the first argument, resulting in 4560
| - | the n mode applies to the second argument, resulting in 03db
| - | the c mode is repeated (sign *) for all the remaining arguments, resulting in 0c0d.
|
|
The unpack function retrieves into an array, the numbers that have been packed in a string. The result can be signed.
These are the principal results:
- | in H or h modes, a single unpacked string is returned in an one-item array. Each octet of the packed string is expanded into the two octets representing the two hexadecimal numbers contained in it. In H mode, the resulting octets are in the same order as the nibbles from which they derive; in h mode, the order is reversed.
|
- | in C and c modes, the octets of the packed string are retieved and transformed into a number, fron 0 to 255 with C (uppercase C), from -128 to 127 with c (lowercase c).
|
- | in S and s modes, each octet pair of the packed string is transformed into a number, fron 0 to 65535 with S (uppercase S), from -32768 to 32767 with s (lowercase s).
|
- | in I and i modes, each group or 4 octets of the packed string is transformed into a number, fron 0 to 4294967296 with I (uppercase I), from -2147463648 to 214746364è with i (lowercase i).
|
Example:
TestUnpack.php
<?php
$a = "12345ABCDE";
$x = pack ("H*c*",$a, 255,255);
print bin2hex($x)."<br>";
$y = unpack('H*', $x);
foreach ($y as $v){
print "$v<br>\n";
}
$y = unpack('C*', $x);
foreach ($y as $v){
print "$v \n";
}
print "<br>pack c, 255, 127, ...<br>";
$x = pack("c*",255,127,128,129,260);
print bin2hex($x)."<br>";
print "<br>unpack C<br>";
$y = unpack('C*', $x);
foreach ($y as $v){
print "$v<br>\n";
}
print"<br>unpack c<br>";
$y = unpack('c*', $x);
foreach ($y as $v){
print "$v<br>\n";
}
print "<br>unpack H<br>";
$y = unpack('H*', $x);
foreach ($y as $v){
print "$v<br>\n";
}
print"<br>pack s /unpack";
$x = pack("s*",32767,32768,65540);
$y = unpack('s*', $x);
foreach ($y as $v){
print "$v<br>\n";
}
?>
|
12345ABCDE
12345abcdeffff
12345abcdeffff
18
52
90
188
222
255
255
pack c, 255, 127, ...
ff7f808104
unpack C
255
127
128
129
4
unpack c
-1
127
-128
-127
4
unpack H
ff7f808104
pack s /unpack
32767
-32768
4
|
In the function argument, the asterisk sign (*) when used with the H mode indicator, indicates that all of the characters in the concerned argument are to be processed. When with the c, C or s mode indicator, it indicates that all of the arguments are to be processed.
The result is shown on the right.
The script first packs the strings '12345ABCDE, 255 and 255, using the mode H for the first, and c for the last two.
The hexadecimal contents of the packed string is printed and appears as 12345abcdeffff. When unpacking this string using the mode H, the result is an array with just one item which, as might be expected is the extended form of the packed string.
This same string is then unpacked using the C mode. The resulting array then contains the octets extracted from the packed string. When printed, each shows the binary number it contains.
Next, the series of numbers 255, 127, 128, 129, 260 is packed using the c mode, then unpacked, using the C, c and H modes.
When packing in the c or C mode (when packing, lowercase c and uppercase C are equivalent), the number to be packed is normally less than 256. When 256 or more, its value modulo 256 is taken into accoount. Therefore, 260 accounts for 4.
When unpacking in the C (upper case) mode, the result is unsigned. In the c (lower case) mode, the result is signed. In the H mode, the unpacked string is returned in an one-item array.
Finally the numbers 32767, 32768 and 65540 are packed, then unpacked in the s mode. In this mode, the numbers are treated modulo 65536.
|
2.10.1 The concepts of class and object
A class is a data structure that contains:
- variables,
- functions to process these variables.
The variables are called properties of the class. The functions are called methods. Properties and methods are members of the class.
An simple example is a class that defines a circle.
This class can, for example, contain:
- | as variables or properties, the circle radius and the unit of length in which the radius is expressed
|
- | as functions or methods, the function that returns the circle radius, area and circumference length, or that sets the radius to some value.
|
The circle area can also be included among the properties. But unless there are specially compelling reasons, this is not recommended, since the area is dependent in the radius, and for one thing, can be derived from it, for another, it can become insconsistent with the radius if the latter is changed.
But much more information can be associated with a class simple as this. For example, the list of units of length that can be used for the measure of the radius. This list can be a set of abbreviations to choose from. And so on...
A class is a descriptive model. From a class objects are derived, which have values assigned to the properties defined for the class. With the class that defines a circle as exemplified above, a derived object has a value assigned to the radius and the unit of length properties.
In a program, an object is assigned to a variable through which the properties and the functions of the object as defined by the class can be used.
2.10.2 Programming aspects
Class definition
The class that defines a circle, as suggested in the foregoing can be described by the following code:
ClassesSample.txt
<?PHP
class Circle {
protected $radius = 0;
private $unit = "";
public $list = array ("inch","cm","pixel","pt");
function getRadius ( ) {return $this->radius;}
function area () {
$a = $this->radius * $this->radius * M_PI;
return $a;
}//end function area
function perimeter ( ) {
$p = 2 * M_PI * $this->radius;
return $p;
}//end function perimeter
function __construct ($x, $y) {
$this->radius = $x;
$this->unit = $y;
}//end function __construct
} //end class Circle
?> |
A class definition is introduced by the keyword class. The contents of the definition are enclosed within curly braces.
The properties of the class are variables which have names conforming to the normal rules for variable names, except that here they are preceded by words such as private, protected or public. These define the visibility attribute of the properties. A property with the private or protected attribute cannot be accessed from outside the class, whereas those with the public property can (we are going to see what this means in a moment).
The methods of the class are functions which are defined the same way as ordinary functions are.
The notation M_PI, used in the script, can be recognized as a constant, since it has no $ sign. It represents the number pi and is readily available from the PHP core.
Note that the code is a PHP sequence, enclosed within the <?PHP and ?> tags.
|
In the functions, you can see notations like:
this is a keyword which designates the object where the code is. The sign -> indicates that the entity named to its right pertains to 'this'. The whole expression $this -> radius identifies the radius property pertaining to the circle object. Note that the $ sign is before the this keyword; there is none before the property name.
|
Object creation
One special function defined in the class is __construct (starting with 2 underscore signs). __construct is a keyword. The function is called upon when an object is created. It is the class constructor.
An object is created using the new operator like this:
$var = new Circle (200, "pixel"); |
|
The function __construct is automatically called. The arguments 100 and "pixel" coded after the class name, are passed to __construct. As it is defined, this function assigns the argument values to the properties $radius and $unit. A Circle object with radius=100, measured in pixel, is created, and assigned to the variable $var.
First of all, the definition of the Circle class must be available to the script where the object is created. This can be provided by coding the class definition somewhere in the script, for example, at the beginning of it (this is not necessary though: the internal class definition need not come before the creation of the object).
But as a class is normally designed for multiple use, its definition would more often be stored in some common file, to be included in a script using the include statement. Now, the include statement has to come before the creation of the object. This is shown in the example below.
An object is an instance of its class. Creating an object is also called instantiating its class.
Using an object
The variable containing the object can be used to access the information contained in the object.
TestObject.php
<?php
include 'ClassesSample.txt';
$var = new Circle (100, "pixel");
$arr = $var->list;
foreach ($arr as $v) {
echo "$v<br>";
}//end foreach
?>
<p>
<?php
echo "radius=".$var->getRadius();
print "<br>";
echo "area=".$var->area();
?>
|
The Circle class definition shown above is contained in the file ClassesSample.txt, along with other classes. The contents of the file is included in the script using the include statement.
The property $list of the object can be directly accessed using the notation:
similar to the $this->radius notation seen in the definition of the class. Here the -> sign indicates that list pertains to the variable $var. The list property can be so accessed because it has the public visibility attribute.
The property $radius of the object cannot be accessed from the script, using $var->radius because it has the protected attribute. The method getRadius executed from inside the object has access to radius, and can return it. The script can get the value of radius by calling the getRadius method. No visibility attribute is apparent for this method. By default it is public, so it can be called.
The notation to use for calling the method is similar to that used for directly accessing a property, except that the parentheses must be present, even though the method has no argument:
|
Another visibility attribute, private, remains to be explained. It prevents, more drastically, a member from being accessed from outside the class. The difference between private and protected will be made clear in connection with the class extension topic.
It is not possible to modify the radius value here, because no method is provided for that. A method making this possible would be:
function setRadius ($x) {
$y = $this -> radius; //save old
$this -> radius = $x; //set new
return $y; //return old
}//end setRadius
|
This method would set the radius to the value specified by its argument, and return the old one.
|
Object destruction
The function __desctruct (starting with 2 underscores) can be defined to handle desired final operations relating to an object. This function, if defined in the class, is automatically given control just before the object is destroyed.
The destruction of an object occurs when the script which uses it terminates, or when the variable that contains it is assigned another value.
2.10.3 Class extension
A class can be used to create another class which extends its capabilities. The extended class retains the properties and methods of the original one, and has added properties and methods.
Here is an example of extending the class Circle into a new class called Cylinder:
ClassCylinder.txt
<?php
class Cylinder extends Circle {
protected $height;
public function area ( ){
$a = 2*M_PI*$this->radius;
$a *= $this->radius + $this->height;
return $a;
}//end area
public function volume (){
$a = parent::area();
$v = $a * $this->height;
return $v;
} //end function volume
public function getHeight(){
return $this->height;
}//end function getHeight
function __construct ($x, $y, $z) {
parent::__construct ($x, $y);
$this->height = $z;
}//end __construct
}//end class Cynlinder
?>
| The script on the left describes the Cylinder class which extends the Circle class. The keyword extends indicates that Cylinder is an extension of Circle, i.e. the properties and methods of Circle are also available in Cylinder, unless redefined here.
The method area is redefined in Cylinder (this is the limiting area of the cylinder made of the areas of the bases plus that of the lateral surface). In the redefinition of this function, the radius property of the Circle class is needed. As it is also part of the Cylinder class, it is identified as $this -> radius.
The method volume is new. It needs the area method of the Circle class. This method is still accessible from inside the Cylinder class, where it is identified as parent::area.
The class Circle is called the parent class of Cylinder. The prefix parent:: is used to distinguish properties and methods of the Circle class, the names of which are redefined in Cylinder.
This is so for the __construct function, the constructor. In the Cylinder constructor function, that of Circle is called to be passed the 2 first arguments $x and $y which are assigned to the $radius and $unit properties.
|
At this point, the distinction between the 3 visibility attributes can be made clear:
- | the private attribute precludes direct access from anywhere but inside the class
|
- | the protected attribute allows direct access from inside the class and from an extension class
|
- | the public attribute allows direct access from anywhere
|
The $radius property of the Circle class is given the protected attribute so that it can be accessed from an extension class like Cylinder.
TestClassExtension.php
<?php
include "ClassesSample.txt";
include "ClassCylinder.txt";
$var = new Cylinder (100, "pixel", 200);
echo "Base radius: ".$var->getRadius();
echo "<br>Height: ".$var->getHeight();
echo "<br>Total area: ".$var->area();
echo "<br>Volume: ".$var->volume();
?> |
|
The script on the left creates an object of the Cylinder class. The description of both classes Cylinder and Circle must be available to the script. This is provided here by including the files ClassesSample.txt and ClassCylinder.txt which contain them. In practice, it would be simpler to include the file ClassesSample.txt which contains the Circle description into ClassCylinder.txt, along with the description of Cylinder
The syntax for creating an object and for accessing the properties and methods of the object are the same as with the parent class Circle.
|
As the class Circle is the parent of Cylinder, the latter is said to inherit or derive from the former.
2.10.4 Encapsulation
The visibility properties private, protected and protected implement the concept of encapsulation which is an important one in object oriented programming. It offers and modulates the protection of the internal contents of an object from the outside.
The private property offers the highest protection, but it isolates the property or method from an extended class. The protected property seems to be the preferrable one in most situation in that it offers protection and at the same time opens the resource of a class to its extensions.
The public property is to be used only if you have good reasons to do so.
2.10.5 Static and constant members
Static members of a class, properties or methods, are accessible without reference to an object of the class. Constants can also be defined for a class, and are also accessible without reference to an object.
A static member is declared by the static keyword which comes after the visibility attribute. A constant, by the const keyword. Example:
StaticMember.cla
<?php
class StaticMember {
public static $var = 0;
const MY_CONSTANT = 23;
public static function calculus ($a, $b) {
$c = $a + $b +self::$var;
$c += self::MY_CONSTANT;
return $c;
}//end calculus
function compute ($x, $y, $z) {
$u = self::calculus ($x, $y);
return $u - $z;
}//end compute
}//end class StaticMember
?>
TestStaticMember.php
<?php
include "StaticMember.cla";
StaticMember::$var = 10;
$x = StaticMember::calculus (12, 17);
echo "var=".StaticMember::$var." x=".$x;
echo "<br>MY_CONSTANT=".StaticMember::MY_CONSTANT;
echo "<br>compute: ";
echo $obj->compute (12, 17, 20);
?>
|
The variable $var and the function calculus are declared static using the keyword static.
The constant MY_CONSTANT is defined using the keyword const. The name of a constants submitted to the same rules as that of a variable. It is recommended to use uppercase although this is not compulsory. A constant name is not preceded by the $ sign.
From within the class, a static member or a constant, is identified using the self:: notation (the -> notation is not allowed).
In the calling script:
- the variable is identified by the notation StaticMember::$var
- the function is identified by the notation StaticMember::calculus(...)
- the constant is identified by the notation StaticMember::MY_CONSTANT
All of these notations use the class name StaticMember followed by the double-colon operator ::
Note the $ sign that precedes the variable name, not the others.
The function compute which is not static must be called through an object.
|
2.10.6 Miscellany
The __autoload function (PHP 5)
To avoid having to use the include statement for every file that contains a class to use, you can define an __autoload (2 starting underscores) function in the script, which will automatically be called to load the class file whenever needed. This function has the following syntax:
function __autoload ($x) {
require_once "$x.cla";
}//end __autoload
| where:
.cla | is the file name extension of the files containing the classes
| $x | is any name assigned to the argument
|
|
You have to set each class description in a file having the same name as the class, and the common extension defined in the __autoload function, and set this file in the same directory as the script (this is the meaning of the dot (.) following the argument name, in the function body).
TestAutoLoad.php
<?php
function __autoload ($x) {
require_once "$x.cla";
}//end __autoload
$var = new Cylinder (100, "pixel", 200);
echo "Base radius: ".$var->getRadius();
echo "<br>Height: ".$var->getHeight();
echo "<br>Total area: ".$var->area();
echo "<br>Volume: ".$var->volume();
?>
|
The class Cylinder derives from Circle. They are to be defined in the files called Cylinder.cla and Circle.cla set in the same directory as the script. __autoload will cause these files to be loaded when required.
|
top
Cover
Copyright
Contents
Reference
Index
previous
next