Home >Backend Development >PHP Tutorial >Active scope of variables_PHP tutorial
The scope of a variable is limited to the context in which it is defined. There are only single scopes for all PHP variables in most sections. However, in user-defined functions, a concept of local function scope is introduced. Any variables used in this function are by default restricted to the function's local scope. For example:
$a = 1; /* global scope */
Function Test () {
echo $a; /* reference to local scope variable */ }
Test () ;
This script will not cause any output, because the declaration of the variable "$a" is submitted to the local translation, and this variable is not assigned a value in its active scope. You can notice that this is a little different from C, where global variables are automatically made available unless otherwise specified in the function. This can cause many problems in a program because people can accidentally change the value of a global variable. In PHP global variables must be declared in a function if you want to use it in this function. Examples are as follows:
$a = 1;
$b = 2;
Function Sum () {
global $a, $b;
$b = $a + $ b;
}
Sum ();
echo $b;
The above script will output "3". Global variables $a and $b are declared in the function, and any references to these two variables are assigned to the global variables. There is no limit on the number of global variables that functions can operate on.
The second way to accept global variables is to use PHP's special definition array $GLOBALS. The example is as follows:
$a = 1;
$b = 2;
Function Sum () {
$GLOBALS["b"] = $GLOBALS["a"] + $GLOBALS["b"];
}
Sum ();
echo $b;
The $GLOBALS array is an associative array using "global" as the name of the variable, and the global variable is used as the value of an element in the variable array.