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?
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With