COMP284 Scripting Languages
Lecture 5: PHP (Part 3)
Handouts
Ullrich Hustadt
Department of Computer Science
School of Electrical Engineering, Electronics, and Computer Science
University of Liverpool
Contents
1 Control Structures
Statement Groups
Conditional Statements
Switch Statements
While- and Do While-loops
For-loops
Try, throw, catch, finally statements
2 Functions
Defining a function
Calling a function
Scope of Variables
Functions and HTML
Variable-length argument lists
3 PHP libraries
Include/Require
COMP284 Scripting Languages Lecture 5 Slide L5 1
Control Structures
Control Structures
PHP control structures
statement groups
conditional statements
switch statements
while- and do while-loops
for-loops
try, throw, catch, finally statements
are mostly identical to those of Java
COMP284 Scripting Languages Lecture 5 Slide L5 2
Control Structures Statement Groups
Control Structures: Statement Groups
A statement group is a sequence of zero or more statements delimited
by a pair of curly brackets
{
statements
}
It allows to use multiple statements where PHP expects only one
statement
{
$x = 1;
$y = $x ++;
}
COMP284 Scripting Languages Lecture 5 Slide L5 3
Control Structures Conditional Statements
Conditional Statements
The general format of conditional statements is very similar but not
identical to that in Java and JavaScript:
if ( condition )
statement
elseif ( condition )
statement
else
statement
the elseif-clause is optional and there can be more than one
Note: elseif instead of elif or else if
the else-clause is optional but there can be at most one
COMP284 Scripting Languages Lecture 5 Slide L5 4
Control Structures Conditional Statements
Conditional Statements/Expressions
PHP allows to replace curly brackets with a colon : combined with an
endif at the end of the statement:
if ( condition ):
statements
elseif ( condition ):
statements
else :
statements
endif
This also works for the switch statement in PHP
However, this syntax becomes difficult to parse
when nested conditional statements are used and is best avoided
PHP also supports conditional expressions
condition ? if_tru e _ e x pr : if_fa l s e _e x p r
COMP284 Scripting Languages Lecture 5 Slide L5 5
Control Structures Switch Statements
Switch Statement
A switch statement in PHP takes the following form
switch ( expr ) {
case expr1 :
statements
break ;
case expr2 :
statements
break ;
defaul t :
statements
break ;
}
there can be arbitrarily many case-clauses
the default-clause is optional but there can be
at most one, it does not need to be last
expr is evaluated only once and then compared
to expr1, expr2, etc using (loose) equality ==
once two expressions are found to be equal the
corresponing clause is executed
if none of expr1, expr2, etc are equal to expr,
then the default-clause will be executed
break ‘breaks out’ of the switch statement
if a clause does not contain a break command,
then execution moves to the next clause
COMP284 Scripting Languages Lecture 5 Slide L5 6
Control Structures Switch Statements
Switch Statement: Example
Not every case-clause needs to have associated statements
switch ( $ month ) {
case 1: case 3: case 5: case 7:
case 8: case 10: case 12:
$days = 31;
break ;
case 4: case 6: case 9: case 11:
$days = 30;
break ;
case 2:
$days = 28;
break ;
defaul t :
$days = 0;
break ;
}
COMP284 Scripting Languages Lecture 5 Slide L5 7
Control Structures While- and Do While-loops
While- and Do While-loops
PHP offers while-loops and do while-loops
while ( condition )
statement
do
statement
while ( condition );
Example:
// Compute the factorial of $number
$factorial = 1;
do
$factorial *= $number - -;
while ( $ number > 0);
COMP284 Scripting Languages Lecture 5 Slide L5 8
Control Structures For-loops
For-loops
for-loops in PHP take the form
for ( initia l i s at i on ; test ; increment )
statement
In PHP initialisation and increment can consist of more than one
statement, separated by commas instead of semicolons
Example:
for ( $i = 3, $j = 3; $j >= 0; $i ++ , $j - -)
echo " $i - $j - " , $i * $j , "\n" ;
3 - 3 - 9
4 - 2 - 8
5 - 1 - 5
6 - 0 - 0
COMP284 Scripting Languages Lecture 5 Slide L5 9
Control Structures For-loops
Break and Continue
The break command can also be used in while-, do while-, and for-loops
and discontinues the execution of the loop
while ( $value = array_shift ( $data ) {
$written = fwrite ( $resource , $value );
if (! $ written ) break ;
}
The continue command stops the execution of the current iteration of a
loop and moves the execution to the next iteration
for ( $x = -2; $x <= 2; $x ++) {
if ( $x == 0) continue ;
printf ( " 10 / %2 d = %3 d \n" ,$x ,(10/ $x ));
}
10 / -2 = -5
10 / -1 = -10
10 / 1 = 10
10 / 2 = 5
COMP284 Scripting Languages Lecture 5 Slide L5 10
Control Structures Try, throw, catch, finally statements
Exceptions and error handling
PHP distinguishes between Exceptions and Errors
In PHP 7 both are subclasses of Throwable but not in PHP 5
Exceptions can be thrown via a throw statement
throw new E x c e ption ( message )
where message is a string
User-level errors/warnings/notices can be generated using
trigger_e r r o r ( message [, type ])
where message is a string and type is an integer indicating what type
of error is generated
A try ... catch ... statement allows for exception (throwable)
handling
Since PHP 5.5, a finally clause can be added
try { statements }
catch ( Exception $e ) { s t a t e m e n t s }
finall y { statements }
COMP284 Scripting Languages Lecture 5 Slide L5 11
Control Structures Try, throw, catch, finally statements
Exceptions and error handling
$x = "A" ;
try {
if (( is_in t ( $x ) || is_float ($x )) && is_finite ( $x ))
$y = round ($x ,2);
else
throw new E x c e ption ( "' $x ' is not a number " );
} catch ( Exception $e ) {
echo " Caught : $e \n" ;
$y = 0;
} finally {
echo "y = $y \ n";
}
Caught : Exception : ' A ' is not a number in try . php :7
Stack trace :
#0 { main }
y = 0
COMP284 Scripting Languages Lecture 5 Slide L5 12
Control Structures Try, throw, catch, finally statements
Exceptions and error handling
PHP distinguishes between exceptions and errors
In PHP 5, errors must be dealt with by an error handling function
(‘Division by zero’ produces an error not an exception)
To take advantage of try ... catch ... statements to handle errors,
one can turn errors into exceptions
function ex c ep ti on_error _ ha nd ler ( $errno , $errstr ,
$errfile , $errline ) {
throw new E rr o rE x ce p t io n ( $errstr , $ errno ,
0, $errfile , $errline ); }
set_e r r or _ ha nd le r (" excep t io n_ er ror_hand l er " );
$x = 0;
try {
$y = 1/ $x ;
} catch ( Exception $e ) {
echo " Caught : $e \n" ;
}
Caught : E r ro r E xc e pt i on : Division by zero in try . php :10
COMP284 Scripting Languages Lecture 5 Slide L5 13
Functions Defining a function
Functions
Functions are defined as follows in PHP:
function identifier ( $ param1 , & $ param2 , ...) {
statements
}
Functions can be placed anywhere in a PHP script but preferably they
should all be placed at start of the script (or at the end of the script)
Function names are case-insensitive
The function name must be followed by parentheses
A function has zero, one, or more parameters that are variables
Parameters can be given a default value using
$param = const_expr
When using default values, any defaults must be on the right side of
any parameters without defaults
COMP284 Scripting Languages Lecture 5 Slide L5 14
Functions Defining a function
Functions
Functions are defined as follows in PHP:
function identifier ( $ param1 , & $ param2 , ...) {
statements
}
The return statement
return value
can be used to terminate the execution of a function and to make
value the return value of the function
The return value does not have to be scalar value
A function can contain more than one return statement
Different return statements can return values of different types
COMP284 Scripting Languages Lecture 5 Slide L5 15
Functions Calling a function
Calling a function
A function is called by using the function name followed by a list of
arguments in parentheses
function identifier ( $ param1 , &$ param2 , ...) {
...
}
... identifier ( arg1 , arg2 ,...) ...
The list of arguments can be shorter as well as longer as
the list of parameters
If it is shorter, then default values must have been specified for the
parameters without corresponding arguments
If no default values are available for ‘missing’ arguments,
then we get a PHP fatal error
Example:
function sum ( $num1 , $num2 ) { return $num1 + $num2 ; }
echo " sum : " ,sum (5 ,4) , "\n";
$sum = sum (3 ,2);
COMP284 Scripting Languages Lecture 5 Slide L5 16
Functions Scope of Variables
Variables and Scope
PHP distinguishes the following categories of variables with respect to
scope:
Local variables are only valid in the part of the code
in which they are introduced
(PHP) Global variables are valid outside of functions
Superglobal variables are built-in variables that are always available in
all scopes
Static variables are local variables within a function that retain their
value between separate calls of the function
By default,
variables inside a function definition are local but not static
variables outside any function definition are global
COMP284 Scripting Languages Lecture 5 Slide L5 17
Functions Scope of Variables
Functions and Scope
$x = " Hello ";
function f1 () {
echo " 1: $x \n" ;
}
function f2 () {
echo " 2: $x \n" ;
$x = " Bye " ;
echo " 3: " ,$x ," \ n";
}
f1 ();
f2 ();
echo " 4: $x \n" ;
A variable defined outside any
function is (PHP) global
A (PHP) global variable can be
accessed from any part of the
script that is not inside a function
A variable within a PHP function is
by default local and can only be
accessed within that function
There is no hoisting of variable
‘declarations’
1: PHP Notice : Undefined variable : x
2: PHP Notice : Undefined variable : x
3: Bye
4: Hello
COMP284 Scripting Languages Lecture 5 Slide L5 18
Functions Scope of Variables
Functions and Global Variables
$x = " Hello ";
function f1 () {
global $x ;
echo " 1: $x \n" ;
}
function f2 () {
$x = " Bye " ;
echo " 2: $x \n" ;
global $x ;
echo " 3: $x \n" ;
}
f1 ();
f2 ();
echo " 4: $x \n" ;
1: Hello
2: Bye
3: Hello
4: Hello
A ‘local’ variable can be declared
to be (PHP) global using the
keyword global
All (PHP) global variables with
the same name refer to the same
storage location/data structure
An unset operation removes a
specific variable, but leaves other
(global) variables with the same
name unchanged
COMP284 Scripting Languages Lecture 5 Slide L5 19
Functions Scope of Variables
PHP functions and Static variables
A variable is declared to be static using the keyword static and should
be combined with the assignment of an initial value (initialisation)
function counter () {
static $count = 0;
return $count ++;
}
; static variables are initialised only once
1 function counter () { s tatic $ count = 0; return $count ++; }
2 $co unt = 5;
3 echo " 1: global \ $ count = $ count \n" ;
4 echo " 2: static \ $ count = " , c ounter () , " \n";
5 echo " 3: static \ $ count = " , c ounter () , " \n";
6 echo " 4: global \ $ count = $ count \n" ;
1: global $ count = 5
2: static $ count = 0
3: static $ count = 1
4: global $ count = 5
COMP284 Scripting Languages Lecture 5 Slide L5 20
Functions Scope of Variables
PHP functions: Example
function bubble_sort ( $ array ) {
// $ array , $size , $i , $j are all local
if (! is_array ( $a rray ))
trigger_e r r o r (" Arg u m e nt not an array \n" , E_U S E R _ ER R O R );
$size = count ( $ array );
for ( $i =0; $i < $size ; $i ++) {
for ( $j =0; $j < $size -1 - $i ; $j ++) {
if ( $ar ray [ $j +1] < $arra y [ $j ]) {
swap ( $array , $j , $j +1); } } }
return $array ;
}
function swap (& $array , $i , $j ) {
// swap expects a reference ( to an array )
$tmp = $array [ $i ];
$array [ $i ] = $ array [$j ];
$array [ $j ] = $ tmp ;
}
COMP284 Scripting Languages Lecture 5 Slide L5 21
Functions Scope of Variables
PHP functions: Example
function bubble_sort ( $ array ) {
... swap ( $array , $j , $j +1); ...
return $array ;
}
function swap (& $array , $i , $j ) {
$tmp = $array [ $i ];
$array [ $i ] = $ array [$j ];
$array [ $j ] = $ tmp ; }
$array = array (2 ,4 ,3 ,9 ,6 ,8 ,5 ,1);
echo " Before sorting " , join (", " , $arr ay ) , " \ n";
$sorted = bubble_sort ( $ array );
echo " After s orting " , join (" , " ,$array ) , " \ n";
echo " Sorted array ", join ( ", ", $sor t ed ) , " \ n";
Before sorting 2, 4, 3, 9, 6 , 8 , 5 , 1
After s orting 2, 4 , 3 , 9 , 6 , 8 , 5 , 1
Sorted array 1, 2, 3, 4, 5, 6, 8, 9
COMP284 Scripting Languages Lecture 5 Slide L5 22
Functions Functions and HTML
Functions and HTML
It is possible to include HTML markup in the body of a
function definition
The HTML markup can in turn contain PHP scripts
A call of the function will execute the PHP scripts, insert the output
into the HTML markup, then output the resulting HTML markup
<?php
fu nct io n print _f orm ( $fn , $ ln ) {
?>
< form ac tion = " proces s_ fo rm .php " method = POST " >
<label > Fi rst Name : <inpu t type = " tex t " name =" f" v alu e =" <? php e cho $fn ? >" ></ label >
<br > < label > Last Name <b >* </b >:< input type =" te xt " nam e =" l " value = " <? php echo $ln ? > ">
</label ><br > < input type =" submit " name =" subm it " value =" Subm it " > <inpu t type = reset >
</form >
<?php
}
pr int_for m ( " Ul lrich ", " Hu sta dt ");
?>
< form ac tion = " proces s_ fo rm .php " method = POST " >
<label > Fi rst Name : <inpu t type = " tex t " name =" f" v alu e =" Ullri ch " ></ label >
<br > < label > Last Name <b >* </b >:< input type =" te xt " nam e =" l " value = " Hu stadt ">
</label ><br > < input type =" submit " name =" subm it " value =" Subm it " > <inpu t type = reset >
</form >
COMP284 Scripting Languages Lecture 5 Slide L5 23
Functions Variable-length argument lists
Functions with variable number of arguments
The number of arguments in a function call is allowed to exceed the
number of its parameters
; the parameter list only specifies the minimum number of arguments
int func_num_args()
returns the number of arguments passed to a function
mixed func_get_arg(arg_num)
returns the specified argument, or FALSE on error
array func_get_args()
returns an array with copies of the arguments passed to a function
function sum () { // no minimum numbe r of arguments
if ( func_num _ a r gs () < 1) return null ;
$sum = 0;
foreac h ( func_get _ a r gs () as $value ) { $sum += $ value ; }
return $ sum ;
}
COMP284 Scripting Languages Lecture 5 Slide L5 24
PHP libraries Include/Require
Including and requiring files
It is often convenient to build up libraries of function definitions,
stored in one or more files, that are then reused in PHP scripts
PHP provides the commands include, include_once, require, and
require_once to incorporate the content of a file into a PHP script
includ e ' mylibrary . php ';
PHP code in a library file must be enclosed within a PHP start tag
<?php and an end PHP tag ?>
The incorporated content inherits the scope of the line in which an
include command occurs
If no absolute or relative path is specified, PHP will search for the file
first, in the directories in the include path include_path
second, in the script’s directory
third, in the current working directory
COMP284 Scripting Languages Lecture 5 Slide L5 25
PHP libraries Include/Require
Including and requiring files
Several include or require commands for the same library file
results in the file being incorporated several times
; defining a function more than once results in an error
Several include_once or require_once commands for the same
library file results in the file being incorporated only once
If a library file requested by include and include_once cannot be
found, PHP generates a warning but continues the execution of the
requesting script
If a library file requested by require and require_once cannot be
found, PHP generates a error and stops execution of the requesting
script
COMP284 Scripting Languages Lecture 5 Slide L5 26
PHP libraries Include/Require
PHP Libraries: Example
mylibrary.php
<? php
function bubble_sort ( $ array ) {
... swap ( $array , $j , $j +1); ...
return $array ;
}
function swap (& $array , $i , $j ) {
...
}
?>
example.php
<? php
require_onc e ' mylibrary . php ';
$array = array (2 ,4 ,3 ,9 ,6 ,8 ,5 ,1);
$sorted = bubble_sort ( $ array );
?>
COMP284 Scripting Languages Lecture 5 Slide L5 27
PHP libraries Include/Require
Revision
Read
Chapter 4: Expressions and Control Flow in PHP
Chapter 5: PHP Functions and Objects
of R. Nixon: Learning PHP, MySQL, and JavaScript:
with jQuery, CSS & HTML5. O’Reilly, 2018.
Read
http://uk.php.net/manual/en/language.control-structures.php
http://uk.php.net/manual/en/language.functions.php
http://uk.php.net/manual/en/function.include.php
http://uk.php.net/manual/en/function.include-once.php
http://uk.php.net/manual/en/function.require.php
http://uk.php.net/manual/en/function.require-once.php
of P. Cowburn (ed.): PHP Manual. The PHP Group, 24 Dec 2019.
http://uk.php.net/manual/en [accessed 25 Dec 2019]
COMP284 Scripting Languages Lecture 5 Slide L5 28