Variable scope refers to the regions of code where a variable may be accessed. This is also referred to as visibility. In PHP scope blocks are defined by functions, classes, and a global scope available throughout an application.
Static properties and variables
Static class properties that are defined with the public visibility are functionally the same as global variables. They can be accessed from anywhere the class is defined.
Functions can also define static variables inside their own scope. These static variables persist through multiple function calls, unlike regular variables defined in a function scope. This can be a very easy and simple way to implement the Singleton design pattern:
Superglobal variables are defined by PHP and can always be used from anywhere without the global keyword.
User-defined global variables
The scope outside of any function or class is the global scope. When a PHP script includes another (using include or require) the scope remains the same. If a script is included outside of any function or class, it's global variables are included in the same global scope, but if a script is included from within a function, the variables in the included script are in the scope of the function.
Within the scope of a function or class method, the global keyword may be used to create an access user-defined global variables.
A second way to access variables from the global scope is to use the special PHP-defined $GLOBALS array.
The $GLOBALS array is an associative array with the name of the global variable being the key and the contents of that variable being the value of the array element. Notice how $GLOBALS exists in any scope, this is because $GLOBALS is a superglobal.
This means that the log_message() function could be rewritten as:
One might ask, why use the $GLOBALS array when the global keyword can also be used to get a global variable's value? The main reason is using the global keyword will bring the variable into scope. You then can't reuse the same variable name in the local scope.
This modified text is an extract of the original Stack Overflow Documentation created by following contributors and released under CC BY-SA 3.0