PHP Variables Scope:
PHP has three different variable scopes:
- local
- global
- static
Local variable
Local: A variable declared within a function. These local variables have their scope only in that particular function in which they are declared. This means that these variables cannot be accessed outside the function, as they have local scope.
Any declaration of a variable outside the function with same name as that of the one within the function is a complete different variable.
Global variable
Global:A variables declared outside a function are called global variables. These variables can be accessed directly outside a function. To access the global variable within a function, use the GLOBAL keyword before the variable. However, these variables can be directly accessed or used outside the function without any keyword. Therefore there is no need to use any keyword to access a global variable outside the function.
Using $GLOBALS instead of global
PHP has a predefined superglobal variable called $GLOBALS. It is an associative array with the name of the variable as key and value as the array element. We can use this array variable to add an array of PHP variables in a global scope.
If two variables, local and global, have the same name, then the local variable has higher priority than the global variable inside the function.
Static variable:
It is a feature of PHP to delete the variable, once it completes its execution and memory is freed. Sometimes we need to store a variable even after completion of function execution. Therefore, another important feature of variable scoping is static variable. We use the static keyword before the variable to define a variable, and this variable is called as static variable.
Static variables exist only in a local function, but it does not free its memory after the program execution leaves the scope.