Values & References15 / 16
Up next

Deep clone with __clone

<?php
declare(strict_types=1);
class Inner {
    public int $v = 1;
}
class Outer {
    public Inner $inner;
    public function __construct() {
        $this->inner = new Inner();
    }
    // __clone runs after the shallow copy; deep-copy the nested object
    public function __clone(): void {
        $this->inner = clone $this->inner;
    }
}
$a = new Outer();
$b = clone $a;
$b->inner->v = 42;
// $a->inner stays at 1
echo $a->inner->v, " ", $b->inner->v, "\n";
What you're solving

copy nested objects too