PHP Functions

From Techotopia
Jump to: navigation, search
PreviousTable of ContentsNext
PHP Flow Control and LoopingPHP Arrays


Purchase and download the full PDF and ePub versions of this PHP eBook for only $8.99

Buy eBook


In the world of programming and scripting there are two ways to write code. One way is to write long, sprawling and monolithic sections of script. Another is to break the scripts up into tidy, self contained modules that can be re-used without having to re-invent the same code over and over again. Obviously the latter is highly preferable to the former, and the fundamental building block of this approach to writing PHP scripts is the function.




What is a PHP Function?

Functions are basically named scripts that can be called upon from any other script to perform a specific task. Values (known as arguments) can be passed into a function so that they can be used in the function script, and functions can, in turn, return results to the location from which they were called.

PHP functions exist it two forms, functions that are provided with PHP to make your life as a web developer easier, and those that you as a web developer create yourself.

How to Write a PHP Function

The first step in creating a PHP function is to provide a name by which you will reference the function. Naming conventions for PHP functions are the same as those for variables in that they must begin with a letter or an underscore and must be devoid of any kind of white space or punctuation. You must also take care to ensure that your function name does not conflict with any of the PHP built in functions.

PHP functions are created using the function keyword followed by the name and, finally, a set of parentheses. The body of the function (the script that performs the work of the function) is then enclosed in opening and closing braces.

The following example function simply outputs a string when it is called:

<?php
function sayHello()
{
       print "Hello";
}
?>

Returning a Value from a PHP Function

A single value may be returned from a PHP function to the script from which it was called. The returned value can be any variable type of your choice.

The return keyword is used to return the value:

<?php
function returnTen ()
{
     return 10;
}
?>

The above example returns the value of 10 to the calling script.

Passing Parameters to a PHP Function

Parameters (or arguments as they are more frequently known) can be passed into a function. There are no significant restrictions of the number of arguments which can be passed through to the function.

A function can be designed to accept parameters by placing the parameter names inside the parentheses of the function definition. There are no specific rules on the names that can be given to these arguments other than those applying to variable names in general. In the following examples we will use $arg1 and $arg2 as argument variable names. These variables can then be accessed using the assigned names from within the function body as follows:

<?php
function addNumbers ($arg1, $arg2)
{
     return $arg1 + $arg2;
}
?>

In the above example the addNumbers() function accepts two parameters as arguments assigned to variables arg1 and arg2 respectively, adds them together and returns the result.

Calling PHP Functions

PHP functions are called by using the name declared when the function was defined, together with any values that need to be passed through as parameters. The following example both defines and then calls our addNumbers() function:

<?php
function addNumbers ($arg1, $arg2)
{
     return $arg1 + $arg2;
}

$var1 = 10;
$var2 = 20;
print addNumbers( $var1, $var2);
?>

When loaded into a browser the print statement will display the result returned by the addNumbers() function, in this case the number 30.

Passing Parameters by Reference

In the above example we only passed the values contained in $var1 and $var2 into the addNumbers() function. Had we made any changes to these values in the function the original variables would have remained unchanged. Suppose we change our script so that the function adds 10 to each of the parameters passed in. If we then check the values of the $var1 and $var2 variables after the call to the function we will see they have not been changed:

<?php
function addNumbers ($arg1, $arg2)
{
        $arg1 += 10;
        $arg2 += 10;
        return $arg1 + $arg2;
}

$var1 = 10;
$var2 = 20;

echo "Before var1 = $var1, var2 = $var2 <br>";
addNumbers ($var1, $var2);
echo "After var1 = $var1, var2 = $var2 <br>";

?>

The output from the above script will read:

Before var1 = 10, var2 = 20
After var1 = 10, var2 = 20 

If we wanted the script to work on the actual variables themselves, and change the values of those variables then we do something called passing by reference. This has the effect of passing a reference to the actual variable rather than simply passing the value assigned to the variable. We specify that we are passing by reference by prefixing the variable names in our function definition with an '&' character. If we modify our previous script so that variables are passed by reference:

<?php
function addNumbers (&$arg1, &$arg2)
{
        $arg1 += 10;
        $arg2 += 10;
        return $arg1 + $arg2;
}

$var1 = 10;
$var2 = 20;

echo "Before var1 = $var1, var2 = $var2 <br>";
addNumbers ($var1, $var2);
echo "After var1 = $var1, var2 = $var2 <br>";
?>

In the above example we are now passing by reference, so any changes to the variables passed to the function are changes to the values contained in those variables. In this case the output will read:

Before var1 = 10, var2 = 20
After var1 = 20, var2 = 30

Note that in the above examples we have used variable names $arg1 and $arg2 for the function arguments and $var1 and $var2 for the script fragment that calls the function. It is also valid to use the same names for both the variables and the arguments. For example, the following is valid syntax:

<?php
function addNumbers ($var1, $var2)
{
        $var1 += 10;
        $var2 += 10;
        return $var1 + $var2;
}

$var1 = 10;
$var2 = 20;

echo "Before var1 = $var1, var2 = $var2 <br>";
addNumbers ($var1, $var2);
echo "After var1 = $var1, var2 = $var2 <br>";

?>

Similarly, the same variable names can be used when passing by reference:

<?php
function addNumbers (&$var1, &$var2)
{
        $var1 += 10;
        $var2 += 10;
        return $var1 + $var2;
}

$var1 = 10;
$var2 = 20;

echo "Before var1 = $var1, var2 = $var2 <br>";
addNumbers ($var1, $var2);
echo "After var1 = $var1, var2 = $var2 <br>";
?>

Although the variables and arguments in the first example (where the variables are not passed by reference) share the same name it is important to note that they are still separate, independent variables. In other words, modifying $var1 within the function does not change the value assigned to the $var1 variable declared outside the function. The ability to have two variables with the same name in this context is the result of something called variable scope, a topic that will be covered later in this chapter.

Returning Values by Reference

In addition to passing arguments into a PHP function by reference, it is also possible to return a result by reference. To achieve this, the function name must be prefixed with the '&' character in the function definition and, also at the point at which it is called. In the following example the addNumber() function returns the result by reference:

<?php
function &addNumbers ($arg1, $arg2)
{
        $arg1 += 10;
        $varg2 += 10;
        return $arg1 + $arg2;
}

$myVar = &addNumbers (20, 10);

?>

Functions and Variable Scope

Now that we have covered PHP functions it is time to address an issue relating to variable scope. When a variable is declared outside of a function it is said to have global scope. That is, it is accessible to any part of the PHP script in which it is declared. Conversely, when a variable is declared inside a function it is said to have local scope, in that it is only accessible to the script contained in the body of the function.

This means that you can have a global variable and a local variable with the same name containing different values. In the following example the $myString variable is declared in both local and global scope with different string values:

<?php
function showString ()
{
        $myString = "local string";
        echo "myString = $myString <br>";
}

$myString = "global string";
echo "myString = $myString <br>";
showString();
?>

When executed this will produce the following output:

myString = global string
myString = local string 

Clearly this will be a problem if you ever need to access a global variable in a function with a conflicting local variable name. Fortunately PHP provides the GLOBALS array which provides access to all global variables from within functions. If, therefore, we wanted to access the global version of $myString from within the showString() function, which contains a local version of $myString, we could modify our script as follows:

<?php
function showString ()
{
        $myString = "local string";
        echo "myString = $myString <br>";
        $globalString = $GLOBALS['myString'];
        echo "Global myString = $globalString <br>";
}

$myString = "global string";
echo "myString = $myString <br>";
showString();
?>

This would result in the following output:

myString = global string
myString = local string
Global myString = global string 

Purchase and download the full PDF and ePub versions of this PHP eBook for only $8.99

Buy eBook