Bakalash
Bakalash

Reputation: 553

Remove object reference from array of objects in PHP

Im trying to copy array of objects to a new array. but the reference to the objects in the array are staying the same. my code :

$newArray = $this->ContentArray;
var_dump(newArray[0]->text); //print "text"
var_dump($this->ContentArray[0]->text); //print "text"
$this->ContentArray[0]->text = "edit text"; 
var_dump(newArray[0]->text); //print edit text"

how can I remove the reference to the objects?

Upvotes: 0

Views: 81

Answers (2)

DrSchimke
DrSchimke

Reputation: 96

You could explicitely clone each array element:

$newArray = array_map(
    function ($element) { return clone $element; },
    $this->ContentArray
);
array_merge($this->ContentArray,$newArray);

var_dump(newArray[0]->text);
var_dump($this->ContentArray[0]->text);
$this->ContentArray[0]->text = "edit text"; 
var_dump(newArray[0]->text); 

But I prefer the solution from Praveen Kumar.

Upvotes: 1

isnisn
isnisn

Reputation: 254

You got a typo: $this-ContentArray[0]->text = "edit text";

Should be $this->ContentArray[0]->text = "edit text";

EDIT And you have tried putting '$' before newArray?

EDIT 2

It seems that Objects in PHP are always passed by reference, even if you. You might want to check out this thread: Passed by reference

Upvotes: 0

Related Questions