Created
January 31, 2012 23:56
-
-
Save xurizaemon/1713981 to your computer and use it in GitHub Desktop.
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 | |
*/ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
a is a
b is b
c is c
a is a
b is b
c is b