Keyboard shortcuts

Press ← or → to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

Prototype

The prototype pattern creates new objects by copying an existing, fully-configured instance, called the prototype, rather than instantiating the class and reassembling its state from scratch. It is useful when constructing an object is expensive, such as one built from a database query or a network call, or when the exact concrete class of the object to copy is only known at runtime.

PHP supports this pattern natively through the clone keyword, which creates a shallow copy of an object, duplicating each scalar property directly. Object properties are copied by reference by default, so nested objects still point to the same instance as the original; a class that needs an independent copy of its nested objects implements the __clone() magic method, which PHP calls automatically right after the shallow copy is made, to explicitly clone those nested objects too and produce a genuine deep copy.

<?php

    class Address {
        public function __construct(public string $city) {}
    }

    class Employee {
        public function __construct(public string $name, public Address $address) {}

        public function __clone(): void {
            // without this, both employees would share the same Address instance
            $this->address = clone $this->address;
        }
    }

    $original = new Employee('Ada', new Address('London'));
    $copy = clone $original;
    $copy->address->city = 'Paris';

    echo $original->address->city; // 'London', unaffected by the copy

?>

Documentation

See Also