Values set in object dissappear |
Values set in object dissappear |
DeaPeaJay |
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. |
DeaPeaJay |
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 |
Brian Chandler |
Nov 18 2006, 01:41 AM
Post
#3
|
Jocular coder Group: Members Posts: 2,460 Joined: 31-August 06 Member No.: 43 |
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. |
Lo-Fi Version | Time is now: 26th April 2024 - 06:47 AM |