Skip to content
UoL CS Notes

Control Structures, Functions & Libraries

COMP284 Lectures

Conditional Statements

In addition to the standard curly brace notation we can also use the following notation:

if (condition):
	statement
endif

This must be ended with the statement endif.

It also supports conditional expressions:

condition ? if_true_expr : if_false_expr

Other conditional statements such as:

  • Switch-Case
  • If
  • While & Do-While
  • Break & Continue

are very similar to other languages.

Exceptions & Error Handling

PHP has several classes of error:

  • Exception
  • Error
  • Notice
  • Warning

We can throw exceptions with a throw statement:

throw new Exception(message)
  • message is a string.

Other user-level errors are generated like so:

trigger_error(message [, type])
  • message is a string.
  • type is an integer representing the error level.

We can use the same structures from Java to handle errors:

try { statements }
catch { Exception $e } { statements }
finally { statements }

We can create a useful error handler like so:

$x = 0;
try {
	$y = 1 % $x ;
} catch ( Throwable $e ) {
	echo " Caught : $e \ n " ;
	$y = 0;
} finally {
	echo " y = $y \ n " ;
}
Caught : DivisionByZeroError: Modulo by zero in try.php:3
Stack trace:
#0 {main}
y = 0

Functions

Functions are defined with the following syntax:

function identifier($param1, &$param2, ...) {
	statements
}

To change a variable outside the function then it must be preceded with an ampersand &.

In addition, parameters can have default values:

$param = const_expr

The return value stops execution of the function and returns the associated value:

  • Functions can have more than one return value.
  • The return values don’t have to have the same type.

Calling Functions

We can call functions in the normal way:

identifier(arg1, arg2, ...)
  • We can use a default value by leaving a black space between commas.
  • We can call a function before it is defined.

Type Checking in Functions

As there is no type checking, if we want an input variable to be a particular type, we need to check the type ourselves:

function bubble_sort($array) {
	if (!is_array($array))
		throw new Exception("Argument is not an array.");
	...
}

Functions & HTML

It is possible to include HTML markup in the body of a function:

<?php
	function print_form($fn) {
?>
<form>
	<?php echo $fn?>...
</form>
<?php
}
print_form("test");
?>

A call of the function will execute the PHP, insert the output into the HTML markup and print the markup.

Functions with a Variable Number of Aguments

We can write functions that can take an arbitrary number of arguments:

function sum() {
	if (func_num_args() < 1)
		return 0;
	$sum = 0;
	foreach (func_get_args() as $value)
		$sum += $value;
	return $sum;
}

We can use the following functions:

Function Description
func_num_args() Returns the number of arguments passed to a function.
func_get_arg(arg_num) Returns the specified argument or False on error.
func_get_args() Returns an array with copies of the arguments passed to a function.

Scope

PHP distinguishes the following categories of variables with respect to scope:

  • Local Variables - Only valid in the part of the code in which they are introduces.
  • Global Variables - Are valid outside of functions.
  • Superglobal Variables - Are built-in variables that are always available in all scopes.
  • Static Variables - Local variables within a function that retain their value between separate calls of the function

By default:

  • Variables in a function are local but not static.
  • Variables outside any function are global.

We can access and modify global variables like so:

$x = "Hello";
function fn() {
	global $x;
	echo "$x\n";
}

An unset operation removes a specific variable, but leaves other global variables with the same name unchanged.

We can declare a static variable like so:

static $count = 0;

Including & Requiring Files

  • include - This includes a file in the script but generates a warning if it doesn’t exist.
  • require - This includes a file in the script but generates an error if it doesn’t exist and execution stops.
include 'test.php';

The file we are including must be enclosed in <? php and ?>.

If we want to ensure a file is only included once (to avoid errors) we can use:

  • include_once
  • require_once

If no absolute path is specified PHP will search in the following order:

  1. Directories in the include_path.
  2. The scripts directory.
  3. The current working directory.