In PHP, variables can be declared anywhere in the script.
The scope of a variable refers to the section of the script where it can be accessed or used.
PHP has three distinct variable scopes:
A variable declared outside of a function has a GLOBAL SCOPE and can only be accessed from outside that function.
Variable with global scope:
$x function echo
|
A variable declared within a function has a LOCAL SCOPE and can only be accessed inside that function.
Variable with local scope:
function // using x outside the function will generate an error |
You can have local variables with the same name in different functions since local variables are only recognized within the function where they are declared. |
The global keyword allows you to access a global variable from within a function.
To do this, simply use the global keyword before the variable names inside the function:
$x $y function myTest(); |
PHP also stores all global variables in an array called $GLOBALS[index]
, where the index corresponds to the variable name. This array is accessible from within functions and can be used to update global variables directly.
The previous example can be rewritten as follows:
$x $y
|
Typically, when a function completes execution, all of its variables are deleted. However, there are times when you may want a local variable to persist for future use.
To achieve this, use the static keyword when initially declaring the variable:
function
|
Then, each time the function is called, that variable will retain the information it had from the previous call.
Note: The variable remains local to the function.