note 21799 added to language.variables.scope

From: Date: Mon, 27 May 2002 18:18:12 +0000
Subject: note 21799 added to language.variables.scope
Groups: php.notes 
Request: Send a blank email to php-notes+get-31077@lists.php.net to get a copy of this message
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'. -- http://www.php.net/manual/en/language.variables.scope.php http://master.php.net/manage/user-notes.php?action=edit+21799 http://master.php.net/manage/user-notes.php?action=delete+21799 http://master.php.net/manage/user-notes.php?action=reject+21799

« previous php.notes (#31077) next »