Home >Backend Development >PHP Tutorial >php $GLOBALS super global variable analysis_PHP tutorial
There is a super global variable $GLOBALS in php that is not used by many people. Reasonable use of this variable can make work more efficient. This article mainly analyzes the usage of this super global variable and the difference between $GLOBALS and global.
$GLOBALS definition: refers to all variables available in the global scope (a global combined array containing all variables. The name of the variable is the key of the array). Unlike all other superglobal variables, $GLOBALS is in It is always available anywhere in the PHP code, you can know it by printing the result of the $GLOBALS variable.
In the PHP life cycle, the so-called global variables defined outside the function body cannot be directly obtained inside the function. If you want to access externally defined global variables within the function body, you can access them through global declaration or directly use $GLOBALS, for example:
<?php $var1='www.phpernote.com'; $var2='www.google.cn'; test(); function test(){ $var1='taobao'; echo $var1,'<br />'; global $var1; echo $var1,'<br />'; echo $GLOBALS['var2']; }
The result will be printed as:
taobao
www.phpernote.com
www.google.cn
The following mainly explains the difference between global and $GLOBALS:
$GLOBALS['var'] is the external global variable itself, and global $var is the reference or pointer of the same name of the external $var. That is to say, global generates an alias variable in the function that points to the external variable of the function. Instead of real external variables of the function, $GLOBALS[] actually calls external variables, and they will always be consistent inside and outside the function. Let’s illustrate it with an example:
$var1=1; $var2=2; function test(){ $GLOBALS['var2']=&$GLOBALS['var1']; } test(); echo $var2;
The print result is 1
$var1=1; $var2=2; function test(){ global $var1,$var2; $var2=&$var1; } test(); echo $var2;
The printed result is 2. Why does the printed result be 2? In fact, it is because the reference of $var1 points to the reference address of $var2. The resulting value of the substance has not changed. Let's look at another example.
$var1=1; function test(){ unset($GLOBALS['var1']); } test(); echo $var1;
Because $var1 was deleted, nothing is printed.
$var1=1; function test(){ global $var1; unset($var1); } test(); echo $var1;
The printed result is 1. It proves that only the alias | reference is deleted, and the value itself is not changed in any way. In other words, global $var is actually $var=&$GLOBALS['var']. It's just an alias for calling an external variable.