What is variable scope in PHP, and how does the 'global' keyword and the $GLOBALS array work?

Last updated 15 June 2026

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 global keyword: Declaring global $x; inside a function creates a local reference to the global $x so changes affect it.

  • The $GLOBALS array: A superglobal mapping global variable names to values: $GLOBALS['x'] reaches the same variable without a global declaration.

  • 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
All PHP interview questions