Specifications
The contents of $value have not changed.
This is because of the scope rules. This code creates a variable called $value which contains
10. It then calls the function increment(). The variable $value in the function is created when
the function is called. One is added to it, so the value of $value is 11 inside the function, until
the function ends, and we return to the code that called it. In this code, the variable $value is a
different variable, with global scope, and therefore unchanged.
One way of overcoming this is to declare $value in the function as global, but this means that
in order to use this function, the variable that we wanted to increment would need to be named
$value. A better approach would be to use pass by reference.
The normal way that function parameters are called is called pass by value. When you pass a
parameter, a new variable is created which contains the value passed in. It is a copy of the
original. You are free to modify this value in any way, but the value of the original variable
outside the function remains unchanged.
The better approach is to use pass by reference. Here, when a parameter is passed to a func-
tion, rather than creating a new variable, the function receives a reference to the original vari-
able. This reference has a variable name, beginning with a dollar sign, and can be used in
exactly the same way as another variable. The difference is that rather than having a value of
its own, it merely refers to the original. Any modifications made to the reference also affect the
original.
We specify that a parameter is to use pass by reference by placing an ampersand (&) before the
parameter name in the function’s definition. No change is required in the function call.
The preceding increment() example can be modified to have one parameter passed by refer-
ence, and it will work correctly.
function increment(&$value, $amount = 1)
{
$value = $value +$amount;
}
We now have a working function, and are free to name the variable we want to increment any-
thing we like. As already mentioned, it is confusing to humans to use the same name inside
and outside a function, so we will give the variable in the main script a new name. The follow-
ing test code will now echo 10 before the call to increment(), and 11 afterwards.
$a = 10;
echo $a;
increment ($a);
echo $a ;
Reusing Code and Writing Functions
C
HAPTER 5
5
REUSING CODE
AND
WRITING
FUNCTIONS
139
07 7842 CH05 3/6/01 3:35 PM Page 139