Global Variables
Global variables reside in the global scope, and may be imported in a local scope with the global keyword.
To become a global variable, a variable may use one of the following ways:
- Be declared as such with the
globalkeyword - Be created in the
$GLOBALSvariable, which is a global variable itself - Be created outside any function, method, closure
- Be a super-global
Global variables provide a way to share data in different and remote scopes. They also provide a way for data to be modified by another part of the code, without warning.
<?php
global $count;
$count = 0;
function counter() {
global $count;
// no return here
++$count;
}
counter();
echo $count; // print 1
counter();
echo $count; // print 2
?>
See Also
- How to Declare a Global Variable in PHP?
- PHP Variable Scope Explained: Globals, Superglobals, and Best Practices
Related
- Variables
- Static Variables
- Variable Variables
- $GLOBALS
- global Scope
- Superglobal Variables
- Distributed State
- Hidden State
- Implicit State
- Legacy
- Local Variable