Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you explicitly create a copy of a variable in PHP?

Tags:

I have an array of stdClass objects. When I assign one to a variable, it is not copying the variable but instead referencing the original variable. My code is like this:

for ( $i = 0, $len = count($rows); $i < $len; $i++ ) {     $row = $rows[$i];     echo $rows[$i]->games;     $row->games = 'test';     echo $rows[$i]->games; } 

The first echo outputs the normal value, but the second echo outputs "test". Even though I am setting the property on $row (which should be copied), it's actually setting it on the original array element.

Why is this, and how do I actually create a copy, so that modifying the copy doesn't modify the original?

like image 627
DisgruntledGoat Avatar asked Jan 24 '11 01:01

DisgruntledGoat


People also ask

Which keyword is used to create copy of an object in PHP?

An object copy is created by using the clone keyword (which calls the object's __clone() method if possible). $copy_of_object = clone $object; When an object is cloned, PHP will perform a shallow copy of all of the object's properties.

How do I copy an array in PHP?

The getArrayCopy() function of the ArrayObject class in PHP is used to create a copy of this ArrayObject. This function returns the copy of the array present in this ArrayObject.


1 Answers

Use the clone keyword.

$copy = clone $object; 

important to note:

When an object is cloned, PHP 5 will perform a shallow copy of all of the object's properties. Any properties that are references to other variables, will remain references.

it comes with a nice magic method:

Once the cloning is complete, if a __clone() method is defined, then the newly created object's __clone() method will be called, to allow any necessary properties that need to be changed.

like image 75
Pekka Avatar answered Sep 20 '22 06:09

Pekka