Many people think that the difference between global and $ globals [] is actually not the same.
According to the official explanation
1. $ globals ['var'] is an external global variable.
2. Global $ VaR is an external reference or pointer with the same name as $ var.
For example:
- <? PHP
- $ Var1 = 1;
- $ Var2 = 2;
- Function Test (){
- $ Globals ['var2'] = & $ globals ['var1'];
- }
- Test ();
- Echo $ var2;
- ?>
<? PHP $ var1 = 1; $ var2 = 2; function test () {$ globals ['var2'] = & $ globals ['var1'];} test (); echo $ var2;?>
The normal print result is 1.
- <? PHP
- $ Var1 = 1;
- $ Var2 = 2;
- Function Test (){
- Global $ var1, $ var2;
- $ Var2 = & $ var1;
- }
- Test ();
- Echo $ var2;
- ?>
<? PHP $ var1 = 1; $ var2 = 2; function test () {Global $ var1, $ var2; $ var2 = & $ var1;} test (); echo $ var2;?>
The unexpected result is 2.
Why is the result 2 printed? In fact, it is because the $ var1 reference points to the reference address of $ var2. The actual value is not changed.
Let's look at an example.
- <? PHP
- $ Var1 = 1;
- Function Test (){
- Unset ($ globals ['var1']);
- }
- Test ();
- Echo $ var1;
- ?>
<? PHP $ var1 = 1; function test () {unset ($ globals ['var1']);} test (); echo $ var1;?>
Because $ var1 is deleted, nothing is printed.
- <? PHP
- $ Var1 = 1;
- Function Test (){
- Global $ var1;
- Unset ($ var1 );
- }
- Test ();
- Echo $ var1;
- ?>
<? PHP $ var1 = 1; function test () {Global $ var1; unset ($ var1) ;}test (); echo $ var1 ;?>
Accidentally printed 1. It indicates that only the alias is deleted. | the referenced value is not changed.
Do you understand?
That is to say, global $ VaR is actually $ Var = & $ globals ['var']. Call an alias of an external variable.