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.

$GLOBALS  //An array of all global variables (Like the global keyword, this allows you to 
// access global variables inside a function. for example, as $GLOBALS[‘somevariable’].)
$_SERVER  //An array of server environment variables
$_GET  //An array of variables passed to the script via the GET method
$_POST  //An array of variables passed to the script via the POST method
$_COOKIE  //An array of cookie variables
$_FILES  //An array of variables related to file uploads
$_ENV  //An array of environment variables
$_REQUEST  //An array of all user input including the contents of input including
$_GET, $_POST, and $_COOKIE (but not including $_FILES since PHP 4.3.0)
$_SESSION  //An array of session variables

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.