Prototype Pattern
debt(d7/e3/b3/t7)
Closest to 'only careful code review or runtime testing' (d7), shared-reference bugs from shallow clone don't trigger errors; PHPStan won't flag missing __clone() implementations, surfaces via behavioural testing.
Closest to 'simple parameterised fix' (e3), quick_fix is implementing __clone() on affected classes to deep-copy nested objects — localized change per class but may need it on several types.
Closest to 'localised tax' (b3), the pattern applies where object templates are needed; it's a per-class implementation choice, doesn't shape the whole system.
Closest to 'serious trap' (t7), the misconception explicitly states devs assume clone is deep but it's shallow — contradicts the intuitive meaning of 'clone' and silently shares state across instances.
Also Known As
TL;DR
Explanation
PHP clone creates a shallow copy; __clone() handles deep-copy logic for nested objects. Use cases: expensive-to-create objects, creating variations of a base object, undo/redo snapshots. Without __clone(), nested objects share references between clones.
Common Misconception
Why It Matters
Common Mistakes
- Assuming clone deep-copies
- Not implementing __clone() for nested objects
- State leaking via shared references
Code Examples
$clone = clone $template;
$clone->items->add($extra); // Also modifies $template! Shared reference
class Order {
public function __clone(): void { $this->items = clone $this->items; }
}