Clone
Clone creates a duplicate of an object.
By default, PHP creates a shallow clone: it only makes a copy of the scalar 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 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 a conflict with the readonly properties, until updating readonly during the cloning operation was allowed, in version 8.5.
<?php
class Elephpant {
protected $weight = 1;
function __clone() {
$this->weight = 2;
}
}
// instantiation
$original = new Elephpant;
// cloning
$twin = clone $original;
$secondTwin = clone($original); // parenthesis are now useful
echo $secondTwin->weight; // 2
$customTwin = clone($original, ['weight' => 3]);
echo $customTwin->weight;
?>