On Sat, Oct 23, 2010 at 6:48 PM, Jonathan Sachs <[email protected]> wrote:
> Now that I understand it, I can see the same thing would happen if I
> wrote the equivalent code in C, and probably in Java.
>
Neither C nor Java have references as PHP does, and references in C++ cannot
be changed to point to a new location after being created. None of these
languages have this particular quirk. If you use pointers in C or C++, the
way you assign an address to a pointer makes it clear you are not
overwriting whatever the pointer currently points to, so again it's not a
problem.
In PHP we have a very common pattern of using a reference in foreach(), and
the loop variable continues to reference the last item after the loop exits.
Further, the second loop has to use the iteration variable as a
non-reference. If both loops use a reference variable, the problem
disappears:
$x = array('a', 'b', 'c');
foreach ($x as &$i) echo $i;
> abc
foreach ($x as &$i) echo $i;
> abc
In my opinion, if you write code where a variable is a reference at point X
and a non-reference at point Y, you are asking for trouble. Simply separate
the loops into different functions or introduce a new loop variable.
David