Changes

PHP Functions

1,851 bytes added, 20:43, 31 May 2007
Returning Values By Reference
?>
</pre>
 
== 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 teh 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 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:
 
<pre>
<?php
function showString ()
{
$myString = "local string";
echo "myString = $myString <br>";
}
 
$myString = "global string";
echo "myString = $myString <br>";
showString();
?>
</pre>
 
When executed this will produce the following output:
 
<pre>
myString = global string
myString = local string
</pre>
 
Clearly this will be a problem if you ever need to access a global variable in a function with a conflicting local variable name. Fortynately 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()'' 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:
 
<pre>
myString = global string
myString = local string
Global myString = global string
</pre>