Skip to main content

What It Is

The Prototype pattern creates new objects by cloning an existing one instead of building from zero. You prepare one object as a template, then copy it with PHP's clone keyword and change only what differs.

The one thing to get right: a plain clone copies value properties, but objects inside are shared, not copied. A __clone() method re-copies them, so the clone is truly independent.


Example: A Document Template

The template carries the parts every document repeats. clone copies it — and __clone() re-copies the TagList object inside — so editing the copy leaves the template untouched.

Clone, then change the difference

The report got a new title and an extra tag, and the template still has only [draft] — because __clone() copied the tag list instead of sharing it.

Prompt
Write a PHP script with a Document class (title, footer, and a TagList object holding a tags array) and a __clone method that clones the TagList too, so a cloned document is fully independent. Clone a template into a report, change the report's title and add a tag, then print both to show the template was not affected.
Output: PHP script

When to Use It

Use it when new objects are mostly copies of a prepared one — documents from a template, game entities from a spawner, test data from a fixture.

Skip it when objects are cheap to build fresh, or contain nothing shared. For an object of plain values — strings, numbers, arrays — PHP's bare clone is already a full copy, no __clone() needed.


Pros and Cons

Pros: cheap creation of preconfigured objects; the template documents the defaults; no repeated setup code.

Cons: deep copying is easy to get subtly wrong — a forgotten object property quietly links clone and original; clones drift from the template silently over time.