PHP Variable Scope in Functions
Description
Variables declared outside of functions and classes are global. global variables are available else where in the script.
Function variables are self-contained and do not affect variables in the main script.
Variables from the main script are not implicitly made available inside functions.
Example
Take a look at this example:
<?PHP//from ww w . jav a 2 s . co m
function foo() {
$bar = "java2s.com";
}
$bar = "PHP";
foo();
print $bar;
?>
The code above generates the following result.
Execution of the script starts at the $bar = "PHP"
line,
and then calls the foo()
function.
foo()
sets $bar
to java2s.com, then returns control to the main script where
$bar
is printed out.
Function foo()
is called, and, having no knowledge that a $bar
variable
exists in the global scope, creates a $bar
variable in its local scope.
Once the function ends, all local scopes are gone, leaving
the original $bar
variable intact.