First of all, you do not clone an object by directly calling its __clone
method. You should use the clone
language construct, like this:
$new = clone $old;
That will call your __clone
method for you to do any additional work after the object has been cloned.
Something to note: In PHP, objects are assigned by reference. What this means is that if you clone an object A
which has a variable pointing to an object B
, modifying B
on the original will affect the clone, and vice-versa.
The __clone
method allows you to react when a clone is happening, so you can properly clone B
as well. Like this:
class B { }
class A {
public $b;
public function __construct() {
$this->b = new B();
}
public function __clone() {
$this->b = clone $b;
}
}
$a = new A();
$c = clone $a;
// now you can safely modify $c->b without worrying about $a->b
Note that this nesting should go as deep as you want to receive copies for. Anything else will be copied by reference and can cause headaches down the line. General rule of thumb: be careful with clone.