Global Variables¶
Variables that reside in the global scope, and may be imported with the global keyword.
To become a global variable, a variable may use one of the following ways:
Be declared as such with the
globalkeywordBe created in the
$GLOBALSvariable, which is a global variable itselfBe created outside any function, method, closure
Be a super-global
Global variables provides a way to share data in different and remote scopes. It 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
?>
Related : Variables, Static Variables, Variable Variables, $GLOBALS, global Scope, Superglobal Variables, Distributed State, $GLOBALS, Hidden State, Implicit State, Legacy, Local Variable