A global variable of PHP that refers to the address of a local variable

Source: Internet
Author: User
A global variable for PHP if the address of a local variable is referenced
PHP Code
  
       $b = "DASDF";    Function abc () {        $a = "abc";        Global $b;        $b = & $a;        echo $b. " inner; ";    }    ABC ();    echo $b. ";";


When I output B inside the function, it's ABC, but after we leave the function, output B, and revert to the initial value of DASDF, what's going on? Supposedly, the address of a local variable is quoted, and when the local variable is destroyed, the value of B should be empty.

------Solution--------------------
In the manual:
http://www.php.net/manual/zh/language.references.whatdo.php#example-251
if a variable declared as global is assigned to a reference within a function, the reference is only visible inside the function. You can avoid this by using an array of $GLOBALS.
The reasons are as follows:
take global $var as a shorthand for $var =& $GLOBALS [' var ']; Thus assigning other references to $var only changes the reference to the local variable.
------Solution--------------------
$b = "DASDF";
Function abc () {
$a = "ABC";
Global $b; This is a reference to the $GLOBALS [' B ']
$b = & $a;
$GLOBALS [' bb '] = & $a;
echo $b. " inner; ";
}
ABC (); Abcinner;
echo $b. ";"; DASDF;
Echo $BB; Abc

------Solution--------------------
Remember the two concepts of PHP, all variables are pointers, all scopes are different variables are different variables, you can
  • 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.