note 31522 added to language.references
| From: | chris at chrisderose dot com | Date: | Thu, 24 Apr 2003 21:35:57 +0000 |
| Subject: | note 31522 added to language.references | ||
| Groups: | php.notes | ||
| Request: | Send a blank email to php-notes+get-47048@lists.php.net to get a copy of this message | ||
This caused a good deal of confusion for me today, so I thought I'd share my findings. Though
one might think a variable *should* lose scope at the end of, say, a for() loop. Its really does
not, and any references you set for that variable will continue to point to the variable in question
during the next iteration. So for example:
$first_var = NULL;
for ($i=0;$i<5;$i++) {
$var = "Hello from Iteration $i";
if (!$i)
$first_var = &$var;
}
echo $first_var;
This code snippet prints out: "Hello from Iteration 5" and not "Hello from Iteration
0" as one might expect at first glance.
The reason why this happens is b/c the scope of $var is being retained at the end of the iteration,
and not being unset.
I'm not sure whether this is the expected behavior or if this is a bug. But to accomplish what
we first intended ( "Hello from Iteration 0" ) We should write the above code like so:
$first_var = NULL;
for ($i=0;$i<5;$i++) {
$var = "Hello from Iteration $i";
if (!$i)
$first_var = &$var;
unset($var); // <-- Notice that this is the only difference
}
echo $first_var;
I suspect there's a number of scope issues that are similar to this and that it doesn't
only affect references. But I don't have the time to find out for sure. (I'd be very
interested to hear from someone who does have the time)
--
http://www.php.net/manual/en/language.references.php
http://master.php.net/manage/user-notes.php?action=edit+31522
http://master.php.net/manage/user-notes.php?action=delete+31522
http://master.php.net/manage/user-notes.php?action=reject+31522