Page 1 of 1

foreach by reference

Posted: Tue Jun 28, 2005 9:09 pm
by MathewByrne
Hi,

Just a quick PHP 4 question. I've tried the following which doesn't work (assume $objects is an array of some generic object):

Code: Select all

foreach($objects as $item)
{
   $item->setValue($value);
}
This doesn't actually change the values in $objects at all because they're passed by value rather than by reference. In other words, $item is a copy of an item in the objects array, not the object itself.

I was just wondering if there was a way to use a foreach loop in PHP4 by reference?

Posted: Tue Jun 28, 2005 10:24 pm
by programmermatt

Code: Select all

foreach( $objects as $k=>$v ) {
$objects[$k]->setValue($value);
}
That should work

Posted: Tue Jun 28, 2005 10:27 pm
by neophyte
You could also cast your object as an array before the loop.

Code: Select all

$array = (array) $object;

Posted: Tue Jun 28, 2005 10:39 pm
by MathewByrne
Hmmm, I was hoping there would be something like this that I could do:

Code: Select all

foreach(&$objects as $item)
{
   $item->setValue($value);
}

Posted: Wed Jun 29, 2005 5:03 am
by Weirdan
MathewByrne wrote:Hmmm, I was hoping there would be something like this that I could do: ...
It's implemented in PHP5.

Posted: Wed Jun 29, 2005 6:44 am
by CoderGoblin
I think the following should work in PHP4

Code: Select all

foreach($objects as $key=>$item) {
   $objects[$key]->setValue($value);
}
Let us know...