dan forys

blog

Learning PHP - Part 6: functions

Posted on 2009-11-03 - Comments

Functions are a very important PHP feature, and are the building blocks to some very powerful programming techniques. First of all, what is a function?

In the tutorials so far, the PHP scripts have run from the top down. All instructions are performed in the order they appear in the file.

A function can be thought of as a reusable ‘black box’. You (optionally) give it some data (called arguments or parameters), it performs an operation and (optionally) gives you a result.

This is illustrated in the following diagram:

Diagram of a function

We have already used a function in previous examples; namely ‘isset’:

$isTheVariableSet = isset($someVariable);

In this case, isset takes one argument ($someVariable) and gives you a value of true or false back depending on whether the variable is set or not. This true or false value is assigned the $isTheVariableSet variable in the example.

Functions calls are always written using the function name, followed by opening and closing brackets. The arguments go in the brackets, separated by commas.

Anatomy of a function

PHP has hundreds of functions built-in, but if a native function won’t solve your problem you can build your own.

It is good programming practice to keep function definitions simple: make your function do one thing. You’ll make your code easier to maintain if you keep things simple.

User defined functions take the following form:

function myFunctionName($argument1, $argument2) {
    // Your function code goes here
}

Firstly, you need a specify a name for your function. The name has the same limitations as variables (must start with a letter, or underscore, followed by any number of letters, numbers or underscores). Be sure to call your function something meaningful that describes what it does, avoid names like function1.

Secondly, within the brackets, you specify what inputs (arguments/parameters) you need for your function to work. In PHP the order of these is significant; when calling your function you will need to specify the same arguments in the same order.

Finally, you write the code to make the function work within the curly braces.

Your first function

Let’s start with a really trivial example. A function to generate a string to greet somebody. We’ll call it getGreetingFor(). We’ll give it one argument – the name of the person to greet.

function getGreetingFor($name) {
    $greeting = 'Hello '.$name;
    return $greeting;
}

The function is called like this:

echo getGreetingFor('Dan'); // outputs 'Hello Dan'

When the above code is run, the string ‘Dan’ is assigned to the variable $name inside our function definition. The code inside the function concatenates 'Hello' with the contents of $name, then assigns it to a new variable called $greeting.

The ‘return’ keyword immediately exits the function code and passes back any value associated with it. In this case, it returns the value of $greeting (‘Hello Dan’ in this particular example).

The returned value is then used by the ‘echo’ statement to output the string on the page.

Variable scope

At this point, it’s useful to explain PHP’s concept of variable scope. Scope can be explained in simple terms:

Any variables used inside a function are (usually) not visible outside the function. Likewise, variables declared outside the function are (usually) not visible inside the function.

This can be demonstrated using the example above:

function getGreetingFor($name) {
    $greeting = 'Hello '.$name;
    return $greeting;
}

echo getGreetingFor('Greg'); // outputs 'Hello Greg'
echo $name; // outputs nothing
echo $greeting; // outputs nothing

The variables $name and $greeting used inside the function are not visible outside the function. Instead, you must pass variables in using arguments and get a value out using the return statement. Again, think of functions as self-contained black boxes.

More examples

Functions can have multiple arguments:

function areNamesTheSame($name1, $name2) {
    if ($name1 == $name2) return true;
    return false;
}

if (areNamesTheSame('Philbert', 'Jeremy')) echo 'Philbert and Jeremy are the same'; // Outputs nothing
if (areNamesTheSame('Dan', 'Dan') echo 'Dan and Dan are the same'; // Outputs 'Dan and Dan are the same'

Note that if the names are the same, the return statement on line 2 will exit the function and return true – line 3 is never reached. Conversely, if the names are not the same, it will reach line 3 and return false.

You could use a function to count down from a number:

function countDown($number) {
    $countdownString = ''; // initialise the string
    for ($index = $number; $index >= 0; $index -- {
        $countdownString = $countdownString . $index . ' '; // Adds the current number and a space to $countdownString
    }
    return $countdownString;
}

echo countDown(10) // outputs '10 9 8 7 6 5 4 3 2 1 0 '
echo countDown(3) // outputs '3 2 1 0 '

Arguments with default values

You can make arguments optional by supplying default values. Let’s rewrite the countDown() function:

function countDown($start, $finish = 0) {
    $countdownString = ''; // initialise the string
    for ($index = $start; $index >= $finish; $index -- {
        $countdownString = $countdownString . $index . ' ';
    }
    return $countdownString;
}

echo countDown(10); // outputs '10 9 8 7 6 5 4 3 2 1 0' same as before
echo countDown(10, 5); // outputs '10 9 8 7 6 5'
echo countDown(5, -5); // outputs '5 4 3 2 1 0 -1 -2 -3 -4 -5'

In this case, the $finish argument is optional because it has a default value of 0. This means that if we don’t supply the second argument in the function call, $finish has the value 0.

Note that default parameters must be listed last in the function definition. You can’t for example declare a function like this: function countDown($finish = 0; $start)