☰ See All Chapters |
PHP Variables Scope
PHP has three types of variable scopes:
1. Local variable
2. Global variable
3. Static variable
Local variable
The variables that are declared within a function are called local variables for that function. Scope of variable is limited to function inside which is declared.
<?php function test() { $name = "Manu Manjunatha";//This is local variable echo $name; } test(); ?> |
Output:
Global variable
The variables that are declared outside the function or variables should not be inside any function are called global variables.
<?php $name = "Manu Manjunatha"; // This is local variable
function test() { echo $name; } test(); ?> |
Output:
Static variable
Variable declared inside a function will be destroyed after complete execution of that function. static keyword is used to store a variable even after completion of function execution. static keyword is used before the variable name to make it static a variable.
<?php function test() { static $static_num = 1; $non_static_num = 1; $static_num ++; $non_static_num ++; echo "Static: " . $static_num . "</br>"; echo "Non-static: " . $non_static_num . "</br>"; } // first call test(); // second call test(); ?> |
Output:
GLOBALS keyword
If there are variables with same name inside and outside the functions then to access the global variable you can use GLOBALS keyword. GLOBALS is an array of all global variables. While accessing the global variable $ symbol is not used in array key, but $ should be used before GLOBALS keyword, refer the below example.
<?php $test_var = "I am Global Variable"; function test() { $test_var = "I am Local Variable"; echo $test_var; echo "</br>"; echo $GLOBALS["test_var"]; } test(); ?> |
Output:
global keyword
global keyword is used to reference the global variable if declared inside any function with same name. When a variable is declared with same name as global variable using global keyword, then it references the same global variable. When variable is declared using global keyword, it should not be assigned with value in same line.
If a variable is declared with same name as global variable without global keyword then to access the global variable you should use GLOBALS keyword, in this case local and global variables are different.
<?php $first_name = "Manu"; $last_name = "Manjunatha";
function test() { global $first_name; $first_name = "Advith"; echo $first_name; echo "</br>"; echo $GLOBALS["first_name"];
echo "</br>----------------------</br>";
$last_name = "Tyagraj"; echo $last_name; echo "</br>"; echo $GLOBALS["last_name"]; }
test(); ?> |
Output:
All Chapters