note 31522 deleted from language.references by sniper

From: Date: Tue, 30 Sep 2003 01:19:14 +0000
Subject: note 31522 deleted from language.references by sniper
References: 1  Groups: php.notes 
Request: Send a blank email to php-notes+get-57318@lists.php.net to get a copy of this message
Note Submitter: chris@chrisderose.com ---- 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)

« previous php.notes (#57318) next »