First, let's look at some code.
<?php$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 refers to a local version of the variable $a, and within that range, it is not assigned a value. You may notice that the global variables in PHP are a little different from the C language, and in C, global variables are automatically applied in functions unless overridden by local variables. This can cause some problems, and some people may accidentally change a global variable. Global variables in PHP must be declared globally when used in functions.
Global keyword
First, an example of using global is the following code:
<?php$a = 1; $b = 2; function Sum () { global $a, $b; $b = $a + $b;} Sum (); Echo $b;? >
The output of the above script will be "3". After you declare a global variable $a and $b in a function, all references to either variable point to its global version. PHP has no restrictions on the maximum number of global variables a function can declare.
The second way to access variables globally is to customize $GLOBALS arrays with special PHP. The previous example can be written as:
Example #2 use $GLOBALS instead of global, the code is as follows:
<?php$a = 1; $b = 2; function Sum () { $GLOBALS [' b '] = $GLOBALS [' a '] + $GLOBALS [ ' B '];} Sum (); Echo $b;? >
$GLOBALS is an associative 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. The following example shows the usefulness of a hyper-global variable:
Example #3 Examples of hyper-global variables and scopes
<?phpfunction 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 scope, and they do not require a ' global ' statement. Superglobals was introduced in PHP 4.1.0. echo $_post [' name '];}? >