Prototype Pattern
Also Known As
clone pattern
object cloning
PHP clone
TL;DR
Creating new objects by cloning a prototype — fast when object creation is expensive and variations are needed.
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
✗ PHP clone always creates a deep copy — clone is shallow; nested objects share references unless __clone() explicitly clones them.
Why It Matters
Without Prototype, creating 1000 order templates requires 1000 expensive constructor calls — cloning a template is fast.
Common Mistakes
- Assuming clone deep-copies
- Not implementing __clone() for nested objects
- State leaking via shared references
Code Examples
✗ Vulnerable
$clone = clone $template;
$clone->items->add($extra); // Also modifies $template! Shared reference
✓ Fixed
class Order {
public function __clone(): void { $this->items = clone $this->items; }
}
Tags
🤝 Adopt this term
£79/year · your link shown here
Added
16 Mar 2026
Edited
22 Mar 2026
Views
16
🤖 AI Guestbook educational data only
|
|
Last 30 days
Agents 0
No pings yet today
No pings yesterday
Amazonbot 6
Google 3
Perplexity 2
Unknown AI 2
ChatGPT 2
Ahrefs 1
Also referenced
How they use it
crawler 13
crawler_json 3
Related categories
⚡
DEV INTEL
Tools & Severity
🟢 Low
⚙ Fix effort: Low
⚡ Quick Fix
Use PHP's clone keyword to implement the Prototype pattern — deep clone complex objects with clone and override __clone() to deep-copy nested objects that would otherwise share references
📦 Applies To
PHP 5.0+
web
cli
queue-worker
🔗 Prerequisites
🔍 Detection Hints
Manually recreating complex objects when clone would copy them; shared state bug from shallow copy of object with nested objects
Auto-detectable:
✗ No
phpstan
⚠ Related Problems
🤖 AI Agent
Confidence: Low
False Positives: High
✗ Manual fix
Fix: Medium
Context: Class
Tests: Update