Skip to content

Instantly share code, notes, and snippets.

@xurizaemon
Created January 31, 2012 23:56
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save xurizaemon/1713981 to your computer and use it in GitHub Desktop.
Save xurizaemon/1713981 to your computer and use it in GitHub Desktop.
<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
*/
@xurizaemon
Copy link
Author

a is a
b is b
c is c
a is a
b is b
c is b

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment