If a global variable in PHP references the address of a local variable

Source: Internet
Author: User
If a global variable in PHP references the address of a local variable PHPcode $ B & quot; dasdf & quot; functionabc () {$ a & quot; abc & quot ;; global $ B; $ B & amp; $ a; echo $ B. & quot; inner; & quo if a global variable of PHP references the address of a local variable
PHP code
      $b = "dasdf";    function abc(){        $a = "abc";        global $b;        $b = &$a;        echo $b."inner;";    }    abc();    echo $b.";";


When the function outputs B internally, it is abc, but after leaving the function, the output B is restored to the initial value of dasdf. what is the problem? It is reasonable to say that the address of a local variable is referenced. after the local variable is destroyed, the value of B should be blank.

------ Solution --------------------
In the manual:
Http://www.php.net/manual/zh/language.references.whatdo.php#example-251
If a global variable is assigned to a reference within a function, the reference is only visible within the function. You can avoid this by using the $ GLOBALS array.
The reason is as follows:
Use global $ var as the abbreviation of $ var = & $ GLOBALS ['var. Therefore, assigning other references to $ var only changes the reference of local variables.
------ Solution --------------------
$ B = "dasdf ";
Function abc (){
$ A = "abc ";
Global $ B; // This is a reference to $ GLOBALS ['B '].
$ B = & $;
$ GLOBALS ['BB'] = & $;
Echo $ B. "inner ;";
}
Abc (); // abcinner;
Echo $ B. ";"; // dasdf;
Echo $ bb; // abc

------ Solution --------------------
Remember the two concepts of php. all variables are pointers, and all variables with different scopes are different variables.

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.