Skip to content

Instantly share code, notes, and snippets.

@Xelom
Created February 22, 2017 13:54
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Xelom/2ff7caa5300f0c9a9da1437f1a59d66f to your computer and use it in GitHub Desktop.
Save Xelom/2ff7caa5300f0c9a9da1437f1a59d66f to your computer and use it in GitHub Desktop.
Prototype

In PHP, it can be easily done using clone

class Sheep {
    protected $name;
    protected $category;

    public function __construct(string $name, string $category = 'Mountain Sheep') {
        $this->name = $name;
        $this->category = $category;
    }
    
    public function setName(string $name) {
        $this->name = $name;
    }

    public function getName() {
        return $this->name;
    }

    public function setCategory(string $category) {
        $this->category = $category;
    }

    public function getCategory() {
        return $this->category;
    }
}

Then it can be cloned like below

$original = new Sheep('Jolly');
echo $original->getName(); // Jolly
echo $original->getCategory(); // Mountain Sheep

// Clone and modify what is required
$cloned = clone $original;
$cloned->setName('Dolly');
echo $cloned->getName(); // Dolly
echo $cloned->getCategory(); // Mountain sheep

Also you could use the magic method __clone to modify the cloning behavior.

When to use?

When an object is required that is similar to existing object or when the creation would be expensive as compared to cloning.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment