foreach by reference

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
User avatar
MathewByrne
Forum Commoner
Posts: 38
Joined: Sat Mar 27, 2004 9:49 pm
Location: Australia

foreach by reference

Post 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?
programmermatt
Forum Commoner
Posts: 65
Joined: Tue Mar 15, 2005 5:03 pm
Contact:

Post by programmermatt »

Code: Select all

foreach( $objects as $k=>$v ) {
$objects[$k]->setValue($value);
}
That should work
User avatar
neophyte
DevNet Resident
Posts: 1537
Joined: Tue Jan 20, 2004 4:58 pm
Location: Minnesota

Post by neophyte »

You could also cast your object as an array before the loop.

Code: Select all

$array = (array) $object;
User avatar
MathewByrne
Forum Commoner
Posts: 38
Joined: Sat Mar 27, 2004 9:49 pm
Location: Australia

Post 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);
}
User avatar
Weirdan
Moderator
Posts: 5978
Joined: Mon Nov 03, 2003 6:13 pm
Location: Odessa, Ukraine

Post by Weirdan »

MathewByrne wrote:Hmmm, I was hoping there would be something like this that I could do: ...
It's implemented in PHP5.
User avatar
CoderGoblin
DevNet Resident
Posts: 1425
Joined: Tue Mar 16, 2004 10:03 am
Location: Aachen, Germany

Post 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...
Post Reply