note 31853 deleted from language.references by sniper
| From: | sniper@php.net | Date: | Tue, 30 Sep 2003 01:19:17 +0000 |
| Subject: | note 31853 deleted from language.references by sniper | ||
| References: | 1 | Groups: | php.notes |
| Request: | Send a blank email to php-notes+get-57319@lists.php.net to get a copy of this message | ||
Note Submitter: aflorio@grad.inf.puc-rio.br
----
The first code snippet above is printing "Hello from Iteration 5" not only because PHP
retains variables after a loop, but because you are assigning by reference ($first_var = &$var).
When you do this, $first_var becomes an alias of $var. Whatever changes you make in $var will also
change $first_var (they are actually the same).
If you do:
$first_var = NULL;
for ($i=0;$i<5;$i++) {
$var = "Hello from Iteration $i";
if (!$i)
$first_var = $var; // Assigning by value
}
echo $first_var;
Then you'll get "Hello from Iteration 0".
As you can see, it's not only a matter of variable scoping.