Because in PHP5, Object model is different from PHP4. This seems to be the
correct behavior, because the item you are adding to the array is an object,
which you keep referencing in every iteration of the loop, this would modify
prior assigned values as you advance in the loop. I find instantiating a
"User" object as the first line after fetching a good fix.

- Ammar

On Sun, Mar 9, 2008 at 10:47 AM, Al-Faisal El-Dajani <
[EMAIL PROTECTED]> wrote:

> Hey guys, I'm facing a very weird PHP problem, and would appreciate it if
> someone would explain to me what is going on:
>
> function getUsers()
> {
> $users = array();
> $result = mysql_query("SELECT `id`, `name` FROM `users`");
> while ($row = mysql_fetch_assoc($result)) {
> $user->id = $row['id'];
> $user->name = $row['name'];
> $users[] = $user;
> }
> return $users;
> }
>
> At the end of this function the $users array contains the correct number
> of entries, but they all are the LAST row in the result set. If I print the
> $user object, it shows that it holds the correct data in every iteration. If
> I add unset($user) as the first line in the while loop it works fine. Also,
> if I define a class called user and create a new object in every iteration
> it works fine.
>
> But why is this problem happening here? My guess is that every iteration
> is overwriting the object, but all array entries are referencing the same
> object. Is this is what is happening? if so, why is it happening like so?
>
> --
> Al-Faisal El-Dajani
> Phone: +962-7-79737050
> P.O Box: 140056
> 11814 Amman, Jordan
> >
>

--~--~---------~--~----~------------~-------~--~----~
You received this message because you are subscribed to the Google Groups 
"Jordan PHP Users Group" group.
To post to this group, send email to [email protected]
To unsubscribe from this group, send email to [EMAIL PROTECTED]
For more options, visit this group at http://groups.google.com/group/JoPHP
http://Jolug.org/
-~----------~----~----~----~------~----~------~--~---

Reply via email to