W3docs

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.

In PHP, you can create a copy of an object using the clone keyword.

For example:

Example of creating a copy of an object using the clone keyword in PHP

<?php

class SomeClass
{
    public string $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.

To create a deep copy, you can implement the __clone() magic method. This method is automatically called when you use the clone keyword, allowing you to manually copy nested objects or arrays to break shared references.

Example of using the __clone() magic method to make a deep copy of an object in PHP

<?php

class SomeClass
{
    public string $name = "John";
    public array $settings = ['theme' => 'dark'];

    public function __clone()
    {
        // Deep copy nested data to avoid shared references
        $this->settings = unserialize(serialize($this->settings));
    }
}

$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. By implementing __clone(), you ensure that nested data is deeply copied, preventing the original and the copy from sharing references.