Clone

Clone creates a duplicate of an object.

By default, PHP creates a shallow clone: it only make a copy of the scalars properties, and it keeps the references and any objects untouched. This means that object properties are shared between an object and its clone.

To perform a deep clone, aka to clone an object and its referenced properties, there is the magic method __clone().

Until PHP 8.5, clone was only an operator. Ever since, it is also a native PHP function, which accepts a second argument to update the public properties. That argument prevents from using the magic method __clone, although both may happen at the same time. When __clone and clone() update the same property, the clone() is applied last, and stays.

Cloning had conflict with the readonly properties, until updating readonly during the cloning operation was allowed, in PHP 8.5.

<?php

    class X {
        protected $property = 1;

        function __clone() {
            $this->property = 2;
        }
    }

    // instantiation
    $x = new X;

    // cloning
    $y = clone $x;

    $z2 = clone($x);  // parenthesis are now useful
    echo $z2->property;  // 2
    $z3 = clone($x, ['property' => 3]);
    echo $z3->property;

?>

Documentation

See also What happens when we clone?, Object Cloning, How to clone an object in PHP, PHP Clone All The Things and Clone version 2.

Related : Shallow Clone, Deep Clone, Readonly, References, Object, Identity, Object Type

Added in PHP 4.0+