The scope of a variable in php , which is controlled by the location of the variable’s declaration, determines those parts of the program that can access it. There are four types of variable scope in PHP: local, global, static, and function parameters
Local scope
A variable declared in a function is local to that function. That is, it is visible only to code in that function (including nested function definitions); it is not accessible outside the function. In addition, by default, variables defined outside a function (called global variables) are not accessible inside the function.
For example, here’s a function that updates a local variable instead of a global variable
function updateCounter()
{
$counter++;
}
$counter = 10;
updateCounter();
echo $counter;
10
The $counter inside the function is local to that function, because we haven’t said otherwise. The function increments its private $counter variable, which is destroyed when the subroutine ends. The global $counter remains set at 10
Only functions can provide local scope. Unlike in other languages, in PHP you can’t create a variable whose scope is a loop, conditional branch, or other type of block
Global scope
Variables declared outside a function are global. That is, they can be accessed from any part of the program. However, by default, they are not available inside functions. To allow a function to access a global variable, you can use the global keyword inside the function to declare the variable within the function.
Here’s how we can rewrite the updateCounter() function to allow it to access the global $counter variable:
function updateCounter()
{
global $counter;
$counter++;
}
$counter = 10;
updateCounter();
echo $counter;
11
A more cumbersome way to update the global variable is to use PHP’s $GLOBALS array instead of accessing the variable directly
function updateCounter()
{
$GLOBALS[counter]++;
}
$counter = 10;
updateCounter();
echo $counter;
11
Static variables
A static variable retains its value between calls to a function but is visible only within that function. You declare a variable static with the static keyword
For example:
function updateCounter()
{
static $counter = 0;
$counter++;
echo “Static counter is now {$counter}\n”;
}
$counter = 10;
updateCounter();
updateCounter();
echo “Global counter is {$counter}\n”;
Static counter is now 1
Static counter is now 2
Global counter is 10
Function parameters
A function definition can have named parameters:
function greet($name)
{
echo “Hello, {$name}\n”;
}
greet(“Janet”);
Hello, Janet
Function parameters are local, meaning that they are available only inside their functions. In this case, $name is inaccessible from outside greet()