Page 1 of 1

[SOLVED] PHP4 - referring to objects in foreach loop

Posted: Mon Mar 07, 2005 4:28 am
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! :)

Re: PHP4 - referring to objects in foreach loop

Posted: Mon Mar 07, 2005 6:54 am
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.

Posted: Mon Mar 07, 2005 7:09 am
by Jean-Yves
Thanks. :)

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