Page Stats
Visitor: 380
PHP Variable Scope
Variable Scope can be defined as the range of availability of a variable in which it is declared. In PHP, variables can be declared anywhere in the script and has three different variable scopes:
- Local: A variable declared in a function is considered as local variable and can only be accessed within that function.
- Global: A variable declared outside a function has a GLOBAL SCOPE and can only be accessed outside a function. In contrast to local variables, a global variable can be accessed in any part of the program. In order to access a Global variable, place the keyword GLOBAL in front of the variable
- Static: Normally, when a function is completed/executed, all of its variables are deleted. However, sometimes we want a local variable NOT to be deleted. We need it for a further job. In that case we can declare a variable as static.
Example 1: LOCAL SCOPE
Example 2.1: GLOBAL SCOPE
Example 2.2: GLOBAL SCOPE
Example 2.3: GLOBAL SCOPE. PHP stores all global variables in an array called $GLOBALS[index]. The index holds the name of the variable.
Example 3: Static Keyword