70
149
Passing by Reference Versus Passing by Value
You can also use the
global
keyword at the top of a script when a variable is first
used to declare that it should be in scope throughout the script.This is possibly a more
common use of the
global
keyword.
You can see from the preceding examples that it is perfectly legal to reuse a variable
name for a variable inside and outside a function without interference between the two.
It is generally a bad idea,however,because without carefully reading the code and think-
ing about scope,people might assume that the variables are one and the same.
Passing by Reference Versus Passing by Value
If you want to write a function called
increment()
that allows you to increment a
value,you might be tempted to try writing it as follows:
function increment($value, $amount = 1)
{
$value = $value +$amount;
}
This code is of no use.The output from the following test code will be
10
:
$value = 10;
increment ($value);
echo $value;
The contents of
$value
have not changed 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;then you
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 problem is to declare
$value
in the function as global,
but this means that to use this function,the variable that you 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 through an approach dubbed
pass by value.When you pass a parameter, a new variable is created containing 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
function,instead of creating a new variable, the function receives a reference to the orig-
inal variable.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 instead of hav-
ing a value of its own,it merely refers to the original.Any modifications made to the
reference also affect the original.
You 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.