Difference between global and $ globals [''] in PHP

Source: Internet
Author: User

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:

  1. <? PHP
  2. $ Var1 = 1;
  3. $ Var2 = 2;
  4. Function Test (){
  5. $ Globals ['var2'] = & $ globals ['var1'];
  6. }
  7. Test ();
  8. Echo $ var2;
  9. ?>

<? PHP $ var1 = 1; $ var2 = 2; function test () {$ globals ['var2'] = & $ globals ['var1'];} test (); echo $ var2;?>

The normal print result is 1.

  1. <? PHP
  2. $ Var1 = 1;
  3. $ Var2 = 2;
  4. Function Test (){
  5. Global $ var1, $ var2;
  6. $ Var2 = & $ var1;
  7. }
  8. Test ();
  9. Echo $ var2;
  10. ?>

<? 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.

  1. <? PHP
  2. $ Var1 = 1;
  3. Function Test (){
  4. Unset ($ globals ['var1']);
  5. }
  6. Test ();
  7. Echo $ var1;
  8. ?>

<? PHP $ var1 = 1; function test () {unset ($ globals ['var1']);} test (); echo $ var1;?>

Because $ var1 is deleted, nothing is printed.

  1. <? PHP
  2. $ Var1 = 1;
  3. Function Test (){
  4. Global $ var1;
  5. Unset ($ var1 );
  6. }
  7. Test ();
  8. Echo $ var1;
  9. ?>

<? 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.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.