The scope of a variable is the context within which it is defined.
PHP variables can be one of three scope types.
A variable declared in a function is considered local.
Any variable used inside a function is by default limited to the local function scope.
<?php
$a = 1; /* global scope */
function test()
{
$a = 3;
/* reference to local scope variable */
echo "\$a inside of function is $a. <br />";
}
test();
echo "\$a outside of function is $a. <br />";
?>
Output
$a inside function is 1. $a outside of function is 3.
In PHP global variables must be declared global inside a function if they are going to be used in that function.
<?php
$a = 1; /* global scope */
function test()
{
global $a; /* reference to global scope variable */
echo "\$a inside of function is $a. <br />";
}
test();
echo "\$a outside of function is $a. <br />";
?>
Output:
$a inside function is 1. $a outside of function is 1.
Using $GLOBALS instead of global$GLOBALS is a superglobal which is a built-in variables that are always available in all scopes.
<?php
$a = 1; /* global scope */
function test()
{
$GLOBALS['a'] = 3; /* reference to global scope variable */
// variable $a is undefined.
// echo "\$a inside of function is $a. <br />";
}
test();
echo "\$a outside of function is $a. <br />";
?>
Output
$a outside of function is 3.
A static variable exists only in a local function scope, but it does not lose its value when program execution leaves this scope.
To declare a variable to be static, add the keyword STATIC in front of the variable name.
<?php
function test() {
STATIC $count = 0;
echo $count;
echo "<br />";
$count++;
}
test();
test();
test();
?>
$count is initialized only in first call of function$count and increment it.Output:
0 1 2
For the most part all PHP variables only have a single scope. This single scope spans included and required files as well
<?php
$a = 1;
include 'inc.php';
?>
// inc.php <?php echo '$a='.$a; ?>
The $a variable will be available within the included inc.php script.
Output:
$a=1