1.global
The role of global is to define globals, but this global variable is not applied to the entire site, but to the current page, including all files of include or require.
However, the global variable defined in the function body can be used within the function body, and the global variable defined outside the function body cannot be used within the function body, as shown in the following example.
(1) Define the global variable in the function body, which can be used within the function body.
<? PHP $a = 123; function AA () {global $a;//define $ A as the Global variable. echo $a; Calling variables outside the body of the function} AA (); The output is 123, indicating that the function body can use variables outside the body of the function;?>
(2) Define the global variable outside the function body, which is not available in the function body.
<? PHP $a = 123; Global $a; Define $ A as a global variable outside the function body. function aa () { echo $a;} AA ();//Will error, cannot output variable a.?>
2. $GLOBALS
In the $GLOBALS array, each variable is an element, the key name corresponds to the variable name, and the value corresponds to the contents of the variable. $GLOBALS exists globally because $GLOBALS is a hyper-global variable. Note the $globals, such as the variable $a1, written as $globals[' A1 '.
Example: Use global definition first
<? PHP $a 1 = 1; $a 2 = 2; function Sum () {Global A1, A2;A2 = A1 + A2;//define Change A1 and A2;}sum (); Echo A2; Output is 3?>
Defining global variables using $globals
<? PHP $a 1 = 1; $a 2 = 2;function Sum () {$GLOBALS [' a1 '] = $GLOBALS [' A1 '] + $GLOBALS [' A2 '];//define the variable each to define}sum (); Echo A2; Output is 2?>
Eg:global
function test () { global $a;//define global variable a unset ($a);//delete variable a //print $a;//error, because unset has deleted $ A. } $a = 2; Define a variable atest (); Call the test () method print $a; Output A, the output is actually $ A = 2, so the result is 2.
Eg: $GLOBALS
function Test_global () {global $var 1, $var 2; $var 2 =& $var 1; } function Test_globals () {$GLOBALS [' var3 '] =& $GLOBALS [' var1 '];} $var 1 = 5; $var 2 = $var 3 = 0; Test_global (); Print $var 2; The output result is 0test_globals (); Print $var 3; The result of the output is 5