Press "Enter" to skip to content

Posts tagged as “clone”

Prototype (Clone) Design in PHP

Prototype (or Clone) is a creational design pattern that lets you copy existing objects not dependent on their classes. No need to go through all the fields of the original object and copy their values over to the new object. Simple as one word: CLONE!

<?php

namespace JSTechRoad\Prototype;

// PHP has built-in cloning support.
// Note that the constructor won't be executed during cloning.
// If you have complex logic inside the constructor,
// you may need to execute it in the `__clone` method as well.
class Prototype
{
    public $primitive;
    public $component;
    public $circularReference;

    public function __clone()
    {
        $this->component = clone $this->component;
        $this->circularReference = clone $this->circularReference;
        $this->circularReference->prototype = $this;
    }
}

class ComponentWithBackReference
{
    public $prototype;

    public function __construct(Prototype $prototype)
    {
        $this->prototype = $prototype;
    }
}

function clientCode()
{
    $p1 = new Prototype();
    $p1->primitive = 100;
    $p1->component = new \DateTime();
    $p1->circularReference = new ComponentWithBackReference($p1);

    $p2 = clone $p1;
    if ($p1->primitive === $p2->primitive) {
        echo "Primitive field values have been carried over to a clone.\n";
    } 
    if ($p1->component === $p2->component) {
        echo "Simple component has not been cloned.\n";
    }
    if ($p1->circularReference === $p2->circularReference) {
        echo "Component with back reference has not been cloned.\n";
    }

    if ($p1->circularReference->prototype === $p2->circularReference->prototype) {
        echo "Component with back reference is linked to original object.\n";
    }
}

clientCode();