What is variable scope in PHP, and how does the 'global' keyword and the $GLOBALS array work?
Last updated
Variable scope defines where a variable is accessible; PHP function bodies have their own local scope and do not see outer variables unless you import them with the global keyword or access them through the $GLOBALS superglobal array.
Local scope: Variables defined inside a function exist only there and vanish when it returns.
Global scope: Variables defined outside functions; unlike many languages, they are NOT automatically visible inside functions.
The
globalkeyword: Declaringglobal $x;inside a function creates a local reference to the global$xso changes affect it.The
$GLOBALSarray: A superglobal mapping global variable names to values:$GLOBALS['x']reaches the same variable without aglobaldeclaration.Best practice: Prefer passing values as parameters and returning results over globals, which create hidden coupling and make testing harder.
[lang:php]
$count = 0;
function increment() {
global $count; // import the global
$count++;
// equivalent: $GLOBALS['count']++;
}
increment();
echo $count; // 1
- https://www.geeksforgeeks.org/php/php-globals/
- https://www.php.net/manual/en/language.variables.scope.php
- https://bhavinom2003.medium.com/variables-scope-static-and-global-5d27aea5121b
- https://stackoverflow.com/questions/12876222/declaring-a-global-array
- https://www.php.net/manual/fr/language.variables.scope.php