I tried to add objects into array in PHP but it didn’t work, tried 2 methods:
#1
$obj->var1 = 'string1';
$obj->var2 = 'string1';
$arr[] = $obj;
$obj->var1 = 'string2';
$obj->var2 = 'string2';
$arr[] = $obj;
#2
$obj->var1 = 'string1';
$obj->var2 = 'string1';
array_push($arr,$obj);
$obj->var1 = 'string2';
$obj->var2 = 'string2';
array_push($arr,$obj);
Both methods will add the latest object into entire array. Seems that object is added to the array by reference. Is there a way to add they into array by value ?
Objects are always passed by reference in php 5 or later. If you want a copy, you can use the clone operator
$obj = new MyClass;
$arr[] = clone $obj;
Answer:
You have to first clone the object before making modifications:
$obj->var1 = 'string1';
$obj->var2 = 'string1';
$arr[] = $obj;
$obj = clone $obj; // Clone the object
$obj->var1 = 'string2';
$obj->var2 = 'string2';
$arr[] = $obj;
Answer:
In PHP 5, objects are passed by reference unless you specifically say otherwise.
Here, you probably want to clone
the object when you add it to the array:
$obj->var1 = 'string1';
$obj->var2 = 'string1';
$arr[] = clone $obj;
$obj->var1 = 'string2';
$obj->var2 = 'string2';
$arr[] = clone $obj;
Answer:
Try this:
$arr[] = clone $obj;