Specifications
The following code produces no output. Here we are declaring a variable called $var inside
our function fn(). Because this variable is declared inside a function, it has function scope and
only exists from where it is declared, until the end of the function. When we again refer to
$var outside the function, a new variable called $var is created. This new variable has global
scope, and will be visible until the end of the file. Unfortunately, if the only statement we use
with this new $var variable is echo, it will never have a value.
function fn()
{
$var = “contents”;
}
echo $var;
The following example is the inverse. We declare a variable outside the function, and then try
to use it within a function.
function fn()
{
echo “inside the function, \$var = “.$var.”<br>”;
$var = “contents2”;
echo “inside the function, \$var = “.$var.”<br>”;
}
$var = “contents 1”;
fn();
echo “outside the function, \$var = “.$var.”<br>”;
The output from this code will be as follows:
inside the function, $var =
inside the function, $var = contents 2
outside the function, $var = contents 1
Functions are not executed until they are called, so the first statement executed is
$var = “contents 1”;. This creates a variable called $var, with global scope and the con-
tents
“contents 1”. The next statement executed is a call to the function fn(). The lines
inside the statement are executed in order. The first line in the function refers to a variable
named
$var. When this line is executed, it cannot see the previous $var that we created, so it
creates a new one with function scope and echoes it. This creates the first line of output.
The next line within the function sets the contents of $var to be “contents 2”. Because we
are inside the function, this line changes the value of the local $var, not the global one. The
second line of output verifies that this change worked.
The function is now finished, so the final line of the script is executed. This echo statement
demonstrates that the global variable’s value has not changed.
Reusing Code and Writing Functions
C
HAPTER 5
5
REUSING CODE
AND
WRITING
FUNCTIONS
137
07 7842 CH05 3/6/01 3:35 PM Page 137