In PHP, scope of a variable, tells where a variable can be accessed(used) or not. On scope basis, PHP has three different scope of variables.
- Global scope
- Local scope
- Static scope
Global scope
Variable declared in global scope can be used anywhere in the PHP code except inside function directly.
<?php
// Global variable
$age = 30;
function myAge(){
echo ($age); // Global variable used inside function directly, gives error.
}
myAge();
echo $age; // used here
?>
$age is declared in Global scope, and used inside function directly, So, PHP gives error Warning: Undefined variable $age in on line 6.
Using Global variable inside function
To use global variable inside function, PHP provide global keyword.
<?php
// Global variable
$age = 30;
function myAge(){
global $age; // used inside function using global keyword
$age = $age + 10;
echo ($age);
}
myAge();
echo $age; // used here
?>
PHP holds global variables in $GLOBALS[index] array. The index holds global variable and can be used by its index.
<?php
$a = 11;
$b = 22;
$c = 0;
function add()
{
$GLOBALS['c'] = $GLOBALS['a'] + $GLOBALS['b'];
}
add();
echo $c;
?>
Local scope
A variable has local scope, when it is declared inside function, such variable can be used inside function only.
<?php
function add(){
$a = 30;
$b = 40;
$c = $a + $b;
echo $c;
}
add();
echo $c; // Gives error
?>
Output:
70
Warning: Undefined variable $c in on line 12
Static scope
In PHP, Inside function, Static allows a variable, to holds it value, after function execution completes or during function calls.
To reuse a function variable value during multiple function calls , use static variable. Non-static variables are deleted after function execution to free memory. so, the values of these variables can’t be reused.
A counter example without static variable
<?php
function myCounter(){
$count = 1;
$count = $count + 1;
echo $count;
}
myCounter();
myCounter();
myCounter();
myCounter();
myCounter();
?>
Output: 22222
myCounter function called 5 times in above example, but due to use of non-static variable, it is not able to hold or retain its previous value, so, it always output 2. because variable gets initialized on every function call.
Counter example with static variable
<?php
function myCounter(){
static $count = 1; // Static variable
$count = $count + 1;
echo $count;
}
myCounter();
myCounter();
myCounter();
myCounter();
myCounter();
?>
Output: 23456
myCounter() function called 5 times, Now static variable is used inside function, because of this, variable can now retain its previous value and outputs 23456.