Page 1 of 1

php objects problem

Posted: Sun Oct 28, 2007 5:43 am
by sarris
i am new to onjects when it comes to php but the problem i amhaving seems really weird.
i have this class

Code: Select all

class thing_obj{
		var $id;
		var $address;
		var $area;
		var $price;
		var $size;
	}
i instantiate the object as

Code: Select all

$temp_obj = new thing_obj();
and create a array

Code: Select all

$array = Array();
and then i have this loop

Code: Select all

$i=0;
while($i<4){
$temp_obj->id = $i;
$array[$i] = $temp_house;
echo  $array[$i]->id;
$i++;

}
and finally i want to see if my data is passed ok

Code: Select all

 echo $array['0']->id;
	echo "--";
	echo $array['1']->id;
	echo "--";
	echo $array['2']->id;
	echo "--";
	echo $array['3']->id;
while he echoes in the loop show 0 1 2 3 as it should the echoes after the loop all show 3...
anyone knows why this is happening??

Posted: Sun Oct 28, 2007 8:14 am
by Stryks
Well ... firstly, it would seem that $temp_house should have been $temp_obj. At least, thats what it would be to get the result you are getting.

The result is due to the fact that objects are passed by reference, particularly so in php 5 (I'm still getting the feel for it myself, so please correct me if I'm wrong here guys).

Anyhow, you enter the while statement, you set the value and then you add it to your array. All is fine on the first run. Then the loop goes through the next iteration, but when you update the value, the change is reflected in all referenced versions of the object. So for each echo hit in the while loop, the output is correct, but afterwards, all array elements are identical - with the last value set.

Basically, at any given time, there is only one instance of that object, despite the fact it's referenced multiple times in an array.

To do this properly, I think you'd do something like ...

Code: Select all

$array = Array();

for ($i = 0; $i < 4; $i++) {
	$array[$i] = new thing_obj();
	$array[$i]->id = $i;
	echo  $array[$i]->id;
}
Again, feel free to jump in and correct me on this guys.

Anyhow, hope this helps you out.