In PHP, global and $ GLOBALS [] are different. many people think that the difference between global and $ GLOBALS [] is just the difference in writing the above code. According to the official explanation, 1. $ GLOBALS [var] is the external global variable itself. 2. global $ var is the reference or pointer of the external $ var with the same name. For example: <? Php ?? $ Var1 ?? 1 ;?? Difference between global and $ GLOBALS [] in $ PHP
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 ;??
- ?> ??
The normal print result is 1.
- <? 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 ;??
- ?> ??
Because $ var1 is deleted, nothing is printed.
- <? 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 for an external variable.