How do I create a copy of an object in PHP?
In PHP, you can create a copy of an object using the clone
keyword.
For example:
<?php
class SomeClass
{
public $name = "John";
}
$original_object = new SomeClass();
$copy_object = clone $original_object;
echo "Original object name: " . $original_object->name . "\n";
echo "Copy object name: " . $copy_object->name . "\n";
This creates a new instance of the object, with the same property values as the original object. Please note that this creates a shallow copy, if the original object has any properties that are references to other objects, the copy will still refer to the same objects.
Watch a video course
Learn object oriented PHP
You can also use serialize and unserialize to make a deep copy of an object
<?php
class SomeClass
{
public $name = "John";
}
$original_object = new SomeClass();
$copy_object = unserialize(serialize($original_object));
echo "Original object name: " . $original_object->name . "\n";
echo "Copy object name: " . $copy_object->name . "\n";
This creates a new instance of the object, with the same property values as the original object and it is a deep copy.