The scope of a variable is the context in which it is defined (that is, its effective scope). Most PHP variables have a single range. This separate scope span also contains the files introduced by include and require. For example:
PHP code
Here the variable $a will take effect in the include file B.inc. However, in a user-defined function, a local function scope is introduced. Any variables that are used inside the function will be limited to the local function in the default context. For example:
PHP code
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:
Example #1 Use Global
PHP code
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
PHP code
$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
PHP code
Global and $globals[] differences
$GLOBALS [' var '] is the external global variable itself, and the global $var is the name of the external $var reference or pointer
PHP code
Results: notice:undefined variable:var1. Because the variable var1 is removed by the unset function.
PHP code
Result: Print 1
The deletion is only an alias reference, and its value is not changed by any of its own.
The global $var is actually the & $GLOBALS [' var '], calling an alias of an external variable.
The $var1 and $globals[' var1 ' in the above code refer to the same variable itself.
PHP's global variable is defined as a global variable, but the global variable is not applied to the entire Web site, but is applied to the current page, including all files of include or require.
Conclusion:
1. $GLOBALS [' var '] is the external global variable itself
2.global $var is a reference or pointer to an external $var with the same name.