Table of Contents
Understanding Global Variables in PHP: Usage and Best Practices
In contrast to local variables, a global variable can be accessed in any part of the program. However, in order to be modified, a global variable must be explicitly declared to be global in the function in which it is to be modified. This is accomplished, conveniently enough, by placing the keyword GLOBAL in front of the variable that should be recognized as global. Placing this keyword in front of an already existing variable tells PHP to use the variable having that name. Consider an example -
Syntax:
<?php
$gVar = 10;
function addFunction() {
GLOBAL $gVar;
$gVar++;
print "gVar is $gVar";
}
addFunction();
?>
Output:
This will produce the following result
gVar is 11