[SOLVED] PHP4 - referring to objects in foreach loop

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
Jean-Yves
Forum Contributor
Posts: 148
Joined: Wed Jul 02, 2003 2:13 pm
Location: West Country, UK

[SOLVED] PHP4 - referring to objects in foreach loop

Post by Jean-Yves »

Can someone explain why if I iterate over an array where the values in the array are objects, referring to the variable that tracks the values does not refer to the original object, but rather refers to a copy?

ie:

Code: Select all

foreach($allLords as $lordID => $lord){
  $lord->setStatus("UPDATED");
}
this does not update the original objects within $allLords.

However:

Code: Select all

foreach($allLords as $lordID => $lord){
  $allLordsї$lordID]->setStatus("UPDATED");
}
Does work.

I have tried adding the ampersand character (for object reference) in front of the key, the array, the value, the assignement, combinations of these. All give an error though.

Is this just the way that PHP4 works, or am I missing something obvious? I suppose that coming from the OO world of Smalltalk, I just assumed that the foreach loop would use a reference to the original array and its objects by default. Mind you, my Smalltalk days are long ago now!

Thanks in advance guys! :)
Last edited by Jean-Yves on Mon Mar 07, 2005 7:12 am, edited 1 time in total.
User avatar
Weirdan
Moderator
Posts: 5978
Joined: Mon Nov 03, 2003 6:13 pm
Location: Odessa, Ukraine

Re: PHP4 - referring to objects in foreach loop

Post by Weirdan »

Jean-Yves wrote: Is this just the way that PHP4 works, or am I missing something obvious?
It's the way PHP4 works. Contrary, in PHP5 foreach loop (

Code: Select all

foreach($array as $value) { 
   $value = rand(); 
}
) $value is a reference to the actual $array element.
User avatar
Jean-Yves
Forum Contributor
Posts: 148
Joined: Wed Jul 02, 2003 2:13 pm
Location: West Country, UK

Post by Jean-Yves »

Thanks. :)

So I'm not going crazy after all! :mrgreen:
Post Reply