Understanding PHP Variable Scope


PHP Scope

In PHP as in other programming languages, scope identifies areas in a program or script where a given variable is visible. There are many scope rules and here are the most important ones.

  • The native super globals can be viewed anywhere in the program.
  • Constants can be used outside as well as inside functions, i.e., they have global visibility.
  • When you define a global variable in a script, that variable will have visibility in all areas of that script except for inside of functions within that same script.
  • Variables that get declared inside of functions as global will refer to the global variables that share the same name.
  • Static variables declared inside of functions can’t be seen outside of the function, but they do retain their value between function calls.
  • Plain vanilla variables inside of functions will be destroyed and unusable once the function has completed its execution.
  • The arrays $_GET and $_POST have special scope rules. They are the well known superglobals with visibility everywhere outside and inside of functions.

The following is a list of superglobal variables. Memorizing these will help as we move on do more in depth features of PHP.

When starting out with PHP, or even if you are more advanced, it is important to be aware of these important aspects of the language. While mundane, having these concepts mastered will allow you to really focus on the cool things you can do with the language once we get to the nitty gritty.