note 20590 rejected from language.variables.scope by didou
| From: | didou@php.net | Date: | Fri, 03 Oct 2003 11:26:30 +0000 |
| Subject: | note 20590 rejected from language.variables.scope by didou | ||
| References: | 1 | Groups: | php.notes |
| Request: | Send a blank email to php-notes+get-57704@lists.php.net to get a copy of this message | ||
Note Submitter: php@klei.cjb.net
----
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)