Clone objects
clone keyword
Assignment copies the handle, not the object. Both variables then point at the same data in memory.
The clone keyword builds a real copy with its own property values. Later edits to the copy leave the source alone.
$order = new stdClass();
$order->total = 10;
$copy = clone $order;
$copy->total = 20;
Customize with __clone
The __clone method runs on the new copy right after cloning. It is the place to reset fields that must stay unique.
Counters, handles, and timestamps are typical candidates. Give the copy fresh values instead of sharing the old ones.
class Cart {
public int $id = 0;
public function __clone(): void {
$this->id = 0;
}
}
Deep copies
Clone copies nested objects by handle, so the copy still points at the same inner object. Edits through one copy would leak into the other.
Clone the inner objects inside __clone to cut that link. Each level of nesting needs its own clone call.
class Order {
public stdClass $box;
public function __construct() {
$this->box = new stdClass();
}
public function __clone(): void {
$this->box = clone $this->box;
}
}
Compare with ==
The == operator reports a match when class and property values match. Different instances with equal data count as equal.
The === operator is stricter and asks for the same instance. Use it when identity matters more than shape.
$a = new stdClass();
$b = new stdClass();
$a->x = 1;
$b->x = 1;
var_dump($a == $b);
var_dump($a === $b);
Next: Serialize objects
Автор статьи: Arthur Isaev