Reusing code and writing functions

Dr Andres Baravalle

Reusing code and writing functions

  • Functions

Functions

Functions

Functions are "a sequence of program instructions that perform a specific task, packaged as a unit" (Wikipedia, 2013)

Functions allow to:

  • Easily reuse code
  • Break-up complex code in separated chunks
  • Organise code into libraries

Core extensions, external extensions and libraries

PHP provides a number of functions, through:

Much of the power of PHP comes from the large number of extensions.

Using functions

As you have already seen, you do not need to write all your PHP code nor be familiar with all the PHP code that you are using.

You have used a number of functions in the past weeks (for example printf() and trim()).

Typically a function:

  • Takes 0 or more input arguments
  • Groups a number of PHP statements (typically operating on the input arguments, if present)

It is common for functions to return a result.

Why functions?

Functions can be called using a single-line statement to complete a task that really requires multiple PHP statements. Even better, usually the developer using the function does not need to know what those statements are.

Because developers do not need to worry about how functions work, functions simplify the development of programs.

To use a function, you only need to know the parameters it requires and the outcome of the function.

The next step is to write your own PHP functions.

Writing functions

A function may be declared (or "defined") using the function keyword:

<?php
function foo($arg_1, $arg_2, /* ..., */ $arg_n){
	echo "Example function.\n";
	return $retval; // $retvar must be defined in the function
}
?>

Let's examine the code:

  • foo is the name of the function
  • curly braces include the body of the function
  • round braces include the parameters of the function: $arg_1 and $arg_2 will be passed when invoking the function
  • please not that the code is incomplete and wouldn't work!

Naming functions

There are both restrictions and conventions when it comes to naming functions.

Restrictions:

  • Cannot have the same name as an exiting function
  • The name can contain only letters, digits and underscores
  • The name cannot start with a digit

Conventions - use one of the following:

  • Camel Case: myFirstFunction()
  • Underscore between words: my_first_function()

Calling functions

Functions are invoked (or ‘called’) by using their name and passing the required parameters:

<?php
foo($arg_a, $arg_b);
?>

The value of $arg_a will be passed (copied) to $arg_1 (see previous slide before) and the value of $arg_b will be passed to $arg_2.

Returning values

Often a function will take some argument, do some computation and then return a value.

This is done using the keyword return.

Activity #1: Hello World

The next step is to write our first function; create a function named hello that:

  • returns "Hello " and the value passed to the function itself as an argument
  • call the function passing "Word" as a parameter and print "Hello World" in the screen (using the function's output)
  • use a loop to process an array of names ("Andres", "Mike", "Gaurav", "Paolo") and use the hello function to tell them hi (e.g. "Hello Andres")

Variable scope

The scope of a variable is the region of code where it is defined and may be used.

A ‘global’ variable has global scope: it can be accessed anywhere in a script (but is not included in the local scope). Other variables such as those declared within a function are ‘local’ variables and may only be accessed within the function.

<?php
$a = 1; // global scope 
              
function test(){ 
	 echo $a; // reference to local scope variable 
} 
              
test(); // this will not work as expected
?> 

The global keyword

The global keyword allows to access variables from the global scope.

<?php
$a = 1;
function increment() {
    global $a;
    $a++;
}
    increment();
    echo $a; // what is the value of $a?
?>
              

The $GLOBAS array

Instead of the global keyword, you can also use the PHP-defined $GLOBALS array.

<?php
$a = 1;
$b = 1;
function increment() {
	$GLOBALS["a"]++;
	$b = 2;
}
increment();
echo $a;
echo $b; // what are the values of $a and $b?
?>

Superglobals

Several predefined variables in PHP are "superglobals", which means they are available in all scopes throughout a script. 

Superglobal variables include $GLOBALS, $_GET and $_POST, amongst others.

Activity #2: Another Hello World

Update the previous activity to create a function that says hi to a number of persons, stored in an array AND uses a custom salutation stored in the global variable $salutation.

Call the function and print "Hola" (or anything you want to have as a salution) and the name of the person.

Static variables

A static variable exists only in a local function scope, but it does not lose its value when program execution leaves this scope.

<?php
function increment() {
	static $a = 0;
	$a++; // a will be incremented each time the function is called
}
?>

Function arguments: passing by value

Arguments allow to pass variables to the function. Values can be passed by value or by reference.

When passing by value (default behavior), the function receives a copy of the value of the original variable. Any modifications to the variable in the function are not reflected in the original.

<?php
function increment($a) {
	$a++; 
}
$a = 10;
increment($a);  
echo $a; // what's the value of $a?
?>

Function arguments: passing by reference (2)

When passing by reference, the function receives a reference to the original variable. Any modifications made to the variable are reflected in the original.

<?php
function increment(&$b) {
	$b++; 
}
$a = 10;
increment($a);  
echo $a; // what's the value of $a?
?>

Activity #3: Area of a rectangle

Create a function that accepts two parameters (width and height) and calculates the area of a rectangle.

The function will then return an associative array including perimeter and area.

You will then use the associative array in the phrase "A rectangle of width $width and height $height has an area of $area and a perimeter of $perimeter.".

Activity #4: Validating triangles (1)

Analyse the structure of the following multi-dimensional array:

<?php
$triangles = array(0 => array(2, 3, 4),
		1 => array(5, 9, 11),
		2 => array(16, 100, 56),
		3 => array(35, 29, 56),
		4 => array(161, 10, 96),
		5 => array(58, 91, 11),
		6 => array(19, 10, 40));
?>			

Activity #4: Validating triangles (2)

Each element of the outer array includes a inner array. The inner array includes 3 integers, representing the sides of a triangle.

Some of those arrays are valid triangles, some are not. Use variables, loops and functions to find out which ones are valid triangles and which ones are not.

Return a line like this:

triangles[0] is (or is not) a valid triangle.

for each of the elements of the array. Read this page on triangles sides to get you started.

Activity #5: Log-in form

Create a log-in form application as below:

  • Create a function (authForm) to output the authentication form
  • Create an authentication function (checkUser), returning false if the username/password pair doesn't exist, and all the user data if it does
    • Include within the function the user array, including usernames, passwords, name and surname
  • Create a page that demonstrates the use of your authentication functions

A demo is available here.

This work

This work is licensed under a Creative Commons Attribution-ShareAlike 3.0 Unported License

Creative Commons License