note 20590 added to language.variables.scope

From: Date: Tue, 09 Apr 2002 09:49:38 +0000
Subject: note 20590 added to language.variables.scope
Groups: php.notes 
Request: Send a blank email to php-notes+get-29000@lists.php.net to get a copy of this message
earlier i saw a message saying: -------------------------------- WARNING! If you create a local variable in a function and then within that function assign it to a global variable by reference the object will be destroyed when the function exits and the global var will contain NOTHING! This main sound obvious but it can be quite tricky you have a large script (like a phpgtk-based gui app ;-) ). example: function foo () { global $testvar; $localvar = new Object (); $testvar = &$localvar; } foo (); print_r ($testvar); // produces NOTHING!!!! hope this helps someone before they lose all their hair -------------------------------- this is wrong. the problem is that, for some unknown reason, the $testvar did not become global. I changed the script a bit to $testvar = "HI!\n"; function foo () { global $testvar; $localvar = "HELLO!\n"; $localvar2 = "GOODBYE!\n"; $testvar = &$localvar; print_r ("1: $testvar"); print_r ("2: {$GLOBALS[testvar]}"); $GLOBALS["testvar"] = &$localvar; print_r ("3: {$GLOBALS[testvar]}"); } foo (); print_r ("4: $testvar"); and everything became ok (besides that $testvar is not global. if anyone knows, please email me the answer) -- http://www.php.net/manual/en/language.variables.scope.php http://master.php.net/manage/user-notes.php?action=edit+20590 http://master.php.net/manage/user-notes.php?action=delete+20590 http://master.php.net/manage/user-notes.php?action=reject+20590

« previous php.notes (#29000) next »