The Web Design Group

... Making the Web accessible to all.

Welcome Guest ( Log In | Register )

 
Reply to this topicStart new topic
> Values set in object dissappear
DeaPeaJay
post Nov 16 2006, 09:41 PM
Post #1


Advanced Member
****

Group: Members
Posts: 103
Joined: 21-September 06
From: East Tennessee - USA
Member No.: 191



I've got an array of User objects. I cycle through each object in a "foreach" loop. I set a value in one of the arrays. Then I cycle throught it again but the value that I set in the first loop is gone.

CODE

foreach($userList as $user){
   echo $user->getFullName() . "<br />";
   $user->setFullName("Susan Harris");
   echo $user->getFullName() . "<br /><br />";
}
foreach($userList as $user){
   echo $user->getFullName() . "<br />";
}


The code above returns this:

Betty Fox
Susan Harris

Betty Fox
Dallas Tester
Jeff Phillips
Jeff Philillps

So, the value stuck the first time through. But on the next for each loop it's as if I'm working with a completely different object. Thanks for any help.
User is offlinePM
Go to the top of the page
Toggle Multi-post QuotingQuote Post
DeaPeaJay
post Nov 17 2006, 07:01 PM
Post #2


Advanced Member
****

Group: Members
Posts: 103
Joined: 21-September 06
From: East Tennessee - USA
Member No.: 191



Well, a friend of mine figured it out if anyone's wondering. Apparently in PHP4 the foreach creates a copy of the objects in the array that you work with. So I ditched the foreach and used a regular for loop as below

CODE

for ($i=1; $i<= sizeof($userList); $i++){
    $userName = $userList[$i]->getUserName();
}


If it were PHP5, I could have kept the foreach and done this:

CODE

foreach($userList as &$user){  <-- Ampersand added
   echo $user->getFullName() . "<br />";
   $user->setFullName("Susan Harris");
   echo $user->getFullName() . "<br /><br />";
}


That ampersand assigns a reference instead of copying the value.
http://us2.php.net/foreach

-David

This post has been edited by DeaPeaJay: Nov 17 2006, 07:02 PM
User is offlinePM
Go to the top of the page
Toggle Multi-post QuotingQuote Post
Brian Chandler
post Nov 18 2006, 01:41 AM
Post #3


Jocular coder
********

Group: Members
Posts: 2,298
Joined: 31-August 06
Member No.: 43



QUOTE(DeaPeaJay @ Nov 18 2006, 09:01 AM) *

Well, a friend of mine figured it out if anyone's wondering. Apparently in PHP4 the foreach creates a copy of the objects in the array that you work with. ...


Yes, I thought it would be something like that - but said nothing since I didn't know the answer. Thanks for the clarifying note.
User is offlinePM
Go to the top of the page
Toggle Multi-post QuotingQuote Post

Reply to this topicStart new topic
2 User(s) are reading this topic (2 Guests and 0 Anonymous Users)
0 Members:

 



- Lo-Fi Version Time is now: 21st August 2018 - 03:11 PM