Programming in PHP

4.28 (118)

Functions

In programming, there is often a process which must be repeated more than once, however, not in the context of loops. This process may need to be repeated several times through the script, at different places. We can contain these processes with functions and procedures. In PHP functions and procedures are the same thing, such that only functions exist.

A function is a sub-process within a program that converts its own inputs to outputs. We have seen some examples of PHP's inbuilt functions such as echo() and count(). These functions take an input value and make an output. In the case of count() the input is an array, and the output is the number of elements in that array.

We can declare our own functions in our scripts, and use them to produce reusable code. This is the notion that we produce code which can be used in other places in our programs, other programs or even other peoples programs. All we have to do, is write a function which does something useful to the inputs to produce an output.

A procedure is a function which does not return a value. Therefore, in PHP it is possible to have functions which do not return any values. This can be particularly useful if we are writing functions to print HTML code to the screen. A function, like any other construct in PHP, has a specific syntax:

Function Syntax
function function_name (input_variable1, input_variable2) {
    statements;
    statements;
}


To declare our very own function, we first use the keyword function followed by the name we are going to give to the function. After this, we write out the input variables within brackets. These input variables, are the names of the variables that we will be able to manipulate within the function. You do not have to have any input variables if you don't want, however, this limits the use of your function. We then surround the statements with curly braces.

Function Example
<?php
/* This function finds the cube of a number */
function findCube ($x) {
    
$cube $x*$x*$x;
    return 
$cube;
}

$name 'John';
$number 3;
$newNumber findCube($number);
echo 
$newNumber;
?>


This example, is a fairly simple example of how to declare a function, and how to use the function in the script. We have declared a function called findCube() which takes one input. The function thinks the input is called $x. Inside the function, we declare a variable called $cube of which we assign the value of the input cubed. We then return this variable.

The code which calls this function is very simple. At first, we declare a variable which holds our number to be cubed. We then have a new variable called $newNumber which will equal the value the function returns. The function name is then written out, with the variable we want to use as input, within the brackets. The process of input variables may seem difficult, as it comes under the topic of scopes.

Scopes, or scopes of variables, are the range of which accessing a variable is valid. In simple terms, a variable cannot be used everywhere. Code inside a function, is contained within the function, and therefore cannot access data that is outside the function. In our example above, the code inside the function could not possibly access the variable $name. As a function cannot access variables outside itself, then it has no direct access to $number. Therefore, you must pass the value to the function, so that it can operate on it. To the function, this is similar to saying $x = $number.

If we were to then modify the value of $x within the function, this would have no effect on $number. Also, code that is outside the function has no access to data inside the function, unless the function returns the value to the main program.

Non-Returning Functions


It is possible to create a function which does not return a value. If you do not require the function to actually provide an output which you can manipulate, then these functions can be useful. However, there are a limited number of things to do that require no output that you will further manipulate. These include, directly writing data to screen and sending data to files / ports (these should actually return a value depicting success or not).

Non-Returning Function
<?php
function writeLine($myStr) {
    echo 
$myStr '<br>';
}

$name 'John';
$greeting 'Hello ' $name;

writeLine($greeting);
writeLine('How are you?');
?>


This is a function which will write out a string to screen, and then add a HTML new line to the end of the string so that it will be displayed on separate lines when viewing the page. The function is almost exactly the same as returning functions, except that there is no return statement telling it what to return. Another small thing to mention is that we have used this function more than once. This is the main purpose of functions, re-use.

More Examples of Functions


Now that we know how to make functions, and know that we pass inputs to them, we can produce our own version of the count() function. The aim of this function is obvious, to take an array as an input and return an integer value which is the number of elements. Note that we only ever return one type of variable. It is standard practice that you cannot return a string one time and an integer another time. In strongly typed languages, this is critical, as if you try to return a variable of the wrong type, your program/script would crash.

Count Example
<?php
function countArray($myArray) {
    
$i 0;
    foreach (
$myArray as $value) {
        
$i++;
    }
    return 
$i;
}

$names[] = 'John';
$names[] = 'Nancy';
$names[] = 'Ted';

$count countArray($names);
echo 
$count;
?>


The above array counting example is quite straight forward. We just declare a function which takes an array as an input, and then we must loop over the array. As we don't know it's size, we must use a foreach-loop to iterate over it. Each time we do one loop, we increment the value of $i by one. At the end, we return the value of $i. In our main code, we declared an array with three elements, hence after we call our new function, the value of $count will be three.

Just a small note: if you declare your function to have an input variable, then when you call your function, you must give it some input. If you do not, then PHP will give you an error telling you that you have not specified an input.

Default Values


One last topic about functions, is the use of default values. As I briefly mentioned before, functions must take an input, if you specified one. This can prove a little bit tricky sometimes to work, as sometimes you want to run the function but are missing some of the input. The solve this, you can specify a default value to an input of your function. This will be the value that the function takes if you fail to give it any other input when you call it.

<?php
function greeting($name 'Anonymous') {
    echo 
'Hello ' $name "\n";
}

greeting('Charles');
greeting('');
greeting();

?>


As you will have noticed, in our input variable declarations, we have set $name = 'Anonymous'. This is telling the function, that if $name does not receive an input, it will use the name Anonymous. In our first call to the function, we have specified a name, so there is nothing special about that. Our second call specifies a blank name. This is interesting, as a blank name is different from a non-existant name. Lastly, we have a non-existant name / no input value so the name Anonymous will be used. The output of this script is:

Hello Charles
Hello
Hello Anonymous


Finally, just to mention that if you are using default values for input variables, then these must be the last variables written in your function declaration. Such that this is valid:

Valid
<?php
function multiply($x$y 3$z 2) {
    return 
$x $y $z;
}
?>


But this isn't:

Invalid
<?php
function multiply($x 2$y 3$z) {
    return 
$x $y z;
}
?>


You must take care in positioning you default and non-default input variables at the right place. Always have standard variables first, followed by default value variables.
Rate this article: BAD 1 2 3 4 5   GOOD
<<     Page 9 of 10    >>

Build Your Own Database Driven Website Using PHP & MySQL

  • Installation instructions for Windows, Linux and Mac OS X
  • Instantly apply working code examples from the book to your Website
  • Build a working Content Management System from scratch
  • Master MySQL database administration
  • Fully updated for PHP 5

       Download FREESample Chapters Now!

Ads

PHPNerds Newsletter