PHP Variable Scope in Functions
In this chapter you will learn:
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 j a v a 2s . c o 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.
Next chapter...
What you will learn in the next chapter:
- What is PHP global variable
- How to create a global variable
- Example
- Example - $GLOBALS Array
- Note for global variables