Variable Scope
Variable Scope
The scope of the variable is the area within which the variable has been created. Based on this a variable can either have a local scope or a global scope or a static scope in PHP.
Global Variable:
A variable which was created in the main body of the code and that can be accessed anywhere in the program is called Global Variable. Global variables can be directly accessed or used in or outside of a function with GLOBAL keyword before variable. However, we can also call them without the global keyword.
For Example:
Output:
Local Variable:
A local variable is created within a function and can be only used inside the function. This means that these variables cannot be accessed outside the function, as they have local scope.
For Example:
Output:
Static Variable:
PHP has a feature that deletes the variable once it has finished execution and frees the memory. When we need a local variable which can store its value even after the execution, we use the static keyword before it and the variable is called static variable.
These variables only exist in a local function and do not get deleted after the execution has been completed.
For Example:
Output: