PHP Variable Scope
The scope of a variable, which is controlled by the location of the
variable’s declaration, determines those parts of the program that
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.
The following code illustrates this:
function update_counter($x)
{
$counter = $x;
echo $counter++;
}
update_counter(10);
This piece of code will display the value 11 during execution. It
has a local variable named counter, which is assigned with the
value of the parameter $x and then incremented. The incremented
value 11 is available only within the function, because it is stored
in a local variable.
Global
Scope:
Variables declared outside a function are called global variables. Global variables can
be accessed from any part of the program. However, by default, they
are not available inside a function.
To allow a function to access a global variable, we have to declare
the same variable inside the function with the global keyword.
Here’s how we can rewrite the update_counter() to allow it
to access the global $counter variable:
function update_counter( )
{
global $counter;
$counter++;
}
$counter = 10;
update_counter();
echo $counter;
This program will display the value 11 as its output. Because the
global variable counter is declared again inside the function
update_counter() as global and then accessed to increment its
content.
Static
Variables:
A static variable is a local variable of a function, but retains its
value between calls to the function. Static variables are declared
using the keyword static. The following program illustrates the use
of static variables:
function update_counter( )
{
static $counter = 0;
$counter++;
echo “This function is called $count time(s)”;
}
update_counter();
update_counter();
update_counter();
The above lines of code will display the message “This function
called … time(s)” 3 times. Each time it displays the
corresponding count value in the output as follows:
This function called 1 time(s)
This function called 2 time(s)
This function called 3 time(s)
Function
Parameters:
Function parameters are variables used for passing values as input to
a function. They are local, meaning that they are available only
within the function, for which they are declared:
function greet($name )
{
echo “Hello, $name \n”;
}
greet(“Raja”);