Global variables are accessible from any scope.
Variables defined in the outermost scope are automatically global and can be used in any scope, such as within a function.
To use a global variable inside a function, you must either declare it as global with the global keyword or access it using the $GLOBALS array.
Access the global variable xxx inside a function:
$x function myfunction() |
This differs from other programming languages, where global variables are accessible without explicitly referring to them as global.
In PHP, referring to a global variable without using the $GLOBALS syntax results in either nothing or an error.
$x function myfunction() |
You can also access global variables within functions by declaring them as global using the global
keyword.
Declare xxx as global within a function:
$x function myfunction() |
Variables created in the outermost scope are global variables, whether they are defined using the $GLOBALS syntax or not.
$x |
Variables created inside a function belong exclusively to that function; however, you can create global variables within a function by using the $GLOBALS
syntax.
Define a global variable within a function and use it outside the function:
function myfunction();
echo |