Specifications

If we want a variable created within a function to be global, we can use the keyword global as
follows:
function fn()
{
global $var;
$var = “contents”;
echo “inside the function, \$var = “.$var.”<br>”;
}
fn();
echo “outside the function, \$var = “.$var.”<br>”;
In this example, the variable $var was explicitly defined as global, meaning that after the func-
tion is called, the variable will exist outside the function as well. The output from this script
will be the following:
inside the function, $var = contents
outside the function, $var = contents
Note that the variable is in scope from the point in which the line global $var; is executed. We
could have declared the function above or below where we call it. (Note that function scope is
quite different from variable scope!) The location of the function declaration is inconsequential,
what is important is where we call the function and therefore execute the code within it.
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 thinking about scope, people
might assume that the variables are one and the same.
Pass by Reference Versus Pass by Value
If we want to write a function called increment() that allows us to increment a value, we
might be tempted to try writing it as follows:
function increment($value, $amount = 1)
{
$value = $value +$amount;
}
This code will be of no use. The output from the following test code will be “10”.
$value = 10;
increment ($value);
echo $value;
Using PHP
P
ART I
138
07 7842 CH05 3/6/01 3:35 PM Page 138