: This article mainly introduces the global keyword and $ GLOBALS usage in PHP. if you are interested in the PHP Tutorial, refer to it.
$a = 1; /* global scope */
function Test()
{
echo $a; /* reference to local scope variable */
}
Test();
?>
This script does not have any output, because the echo statement references a local version of the variable.$In this range, it is not assigned a value. You may notice that the global variables in PHP are a little different from those in C language. in C language, global variables automatically take effect in functions unless they are overwritten by local variables. This may cause some problems. some may accidentally change a global variable. Global variables in PHP must be declared as global when used in functions.
Global keyword
First, useGlobalExample:
Example #1 use global
$a = 1;
$b = 2;
function Sum()
{
global $a, $b;
$b = $a + $b;
}
Sum();
echo $b;
?>
The output of the above script is "3 ". Declare global variables in the function$And$ BAll references to any variable will point to its global version. PHP has no limit on the maximum number of global variables that a function can declare.
The second way to access variables globally is to use a special PHP custom$ GLOBALSArray. The preceding example can be written as follows:
Example #2 use$ GLOBALSReplace global
$a = 1;
$b = 2;
function Sum()
{
$GLOBALS['b'] = $GLOBALS['a'] + $GLOBALS['b'];
}
Sum();
echo $b;
?>
$ GLOBALSIs an associated array. each variable is an element. The key name corresponds to the variable name and the value corresponds to the variable content.$ GLOBALS$ GLOBALS is a super global variable. The following example shows how to use a super global variable:
Example #3 examples of hyperglobal variables and scopes
Function test_global ()
{
// Most of the predefined variables are not "super". they need to use the 'global' keyword to make them valid in the local area of the function.
Global $ HTTP_POST_VARS;
Echo $ HTTP_POST_VARS ['name'];
// Superglobals are valid in any range and they do not require 'global' declarations. Superglobals was introduced in PHP 4.1.0.
Echo $ _ POST ['name'];
}
?>
The above introduces the global keyword and $ GLOBALS usage in PHP, including some content, and hope to be helpful to friends who are interested in PHP tutorials.