
•The scope rules of a language specify how a particular occurrence of a name should be associated with a variable.
PHP Scope Rules
1) Scope of a variable used inside a used defined function is limited to the body of the function by default.
Example 1:
<?php
function test(){
$a = 1;
}
echo $a;
?>
In the above script $a variable is local to the function test. Thus, it is unknown outside the function.
Example 2:
<?php
$a = 1;
function test(){
echo $a;
}
test()
?>
In the above script an error is raised as the variable $a defined outside the function is not visible inside the function.
2) Scope of a variable in a script spans over the files included in a script.
Example :
<?php
$a = 1;
include 'example1.php';
?>
The file example1.php contains the following code :
<?php
echo $a;
?>
The variable $a is visible in the included file “example1.php”.
Global keyword
The keyword global can be used inside functions to refer to variable define outside the function (in the global context).
Syntax:
global $a,$b,……;
<?php
$a = 1;
function test(){
global $a;
echo $a;
}
test();
?>
In the above script the variable $a inside the function binds to the variable $a defined outside the function.
Superglobals
Superglobals are built-in variables that are always available in all scopes. This means the superglobal variables are provided by PHP and are visible everywhere in a script. The PHP superglobals are given in the following list.
* The $GLOBALS variable defines an associative array with the name of the global variable being the key and the contents of that variable being the value of the array element. This variable can be used to access global variables from anywhere in the PHP script.
<?php
$a = 1;
function test(){
echo
$GLOBALS[„a‟];
}
test();
?>
* Static Variables - A variable inside a function can be defined as static to retain its value between function calls. This means that a static variable does not lose its value when program execution leaves the scope.
<?php
function test(){
static $a = 0;
$a = $a + 1;
echo $a;
}
for($i=0; $i<10; $i++){
test();
}
?>
* A static variable can be initialize with a constant value. However, PHP does not allow a static variable to be initialized with the final value of an expression.
<?php
function test(){
static $a = 2 + 3; // incorrect
}