Created
February 1, 2012 00:16
-
-
Save xurizaemon/1714131 to your computer and use it in GitHub Desktop.
Unexpected behaviour when running foreach across an array of objects in PHP
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<pre> | |
<?php | |
/* | |
after using foreach to iterate /by reference/ across an array containing objects, | |
then on the second foreach of the same array, | |
the final member of the array gets overwritten by the previous | |
and c=b | |
if we don't iterate by reference on the first pass, then it doesn't happen | |
and c=c at the end | |
is this right? | |
*/ | |
$array = array( | |
'a' => new stdClass(), | |
'b' => new stdClass(), | |
'c' => new stdClass(), | |
); | |
$array['a']->name = 'a'; | |
$array['b']->name = 'b'; | |
$array['c']->name = 'c'; | |
// by reference | |
foreach ($array as $k => &$value) { | |
print($k . ' is '. $value->name . "\n"); | |
} | |
// no reference this time, but last member gets clobbered | |
foreach ($array as $k => $value) { | |
print($k . ' is '. $value->name . "\n"); | |
} | |
/* | |
a is a | |
b is b | |
c is c | |
a is a | |
b is b | |
c is b <--------------------- | |
*/ | |
// ok, let's try that again | |
// reset the array | |
$array = array( | |
'a' => new stdClass(), | |
'b' => new stdClass(), | |
'c' => new stdClass(), | |
); | |
// some properties | |
$array['a']->name = 'a'; | |
$array['b']->name = 'b'; | |
$array['c']->name = 'c'; | |
// no reference | |
foreach ($array as $k => $value) { | |
print($k . ' is '. $value->name . "\n"); | |
} | |
// again, no reference; last member is OK | |
foreach ($array as $k => $value) { | |
print($k . ' is '. $value->name . "\n"); | |
} | |
/* | |
a is a | |
b is b | |
c is c | |
a is a | |
b is b | |
c is c <--------------------- | |
*/ |
Yeah, PHP has crappy variable scoping. OTOH, they'd probably make lexical scoping suck too.
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
https://bugs.php.net/bug.php?id=49386 is an earlier bug report re the same behaviour. At http://php.net/manual/en/control-structures.foreach.php docs say,
This is still fucked up behaviour.