note 21799 deleted from language.variables.scope by danbrown

From: Date: Mon, 18 May 2009 01:42:59 +0000
Subject: note 21799 deleted from language.variables.scope by danbrown
References: 1  Groups: php.notes 
Request: Send a blank email to php-notes+get-155585@lists.php.net to get a copy of this message
Note Submitter: JeanRobert at Videotron dot ca ---- Comment on May 21. This explanation does not explain why assigning a global variable reference to a globalvariable does not modify it (See the statement "$testvar = &$testvar2" bellow). Here is my own explanation: Inside a function, if we assign a variable reference to a global variable then this global variable is replaced by a new local variable instance. In other words, once done, futur assignment to this variable will only modify the local copy and leave the original global variable unchanged. Looking at the following code will help you to understand it. (Just as a reminder $GLOBALS[testvar] always refers to the original $testvar global variable). $testvar = 1 ; $testvar2 = 2 ; function foo () { global $testvar ; global $testvar2 ; $testvar = 3 ; //Assigning a constant works as expected. echo "$testvar,$GLOBALS[testvar] " ; // 3,3 $testvar = 4 ; //Assigning a variable also works as expected. echo "$testvar,$GLOBALS[testvar] " ; // 4,4 $testvar = &$testvar2 ; // Assiging a reference allocates a new // local testvar instance. echo "$testvar,$GLOBALS[testvar] " ; // 2,4 $testvar=5 ; // Assigning a value to testvar now only modifies // the local instance. echo "$testvar,$GLOBALS[testvar]" ; //5,4 } foo() ; If you plan to assign a variable reference to a global variale then you should use '$GLOBALS[testvar]=&$variable' instead of '$testvar=&$variable'.

« previous php.notes (#155585) next »