Inheritance: implements Prototype
 public function testCopy()
 {
     $str = 'prototype';
     $object1 = new ConcretePrototype($str);
     $this->assertEquals($str, $object1->getName());
     $object2 = $object1->copy();
     $this->assertEquals($str, $object2->getName());
 }
Exemple #2
0
 public static function main()
 {
     $demo = new Demo();
     $demo->array = array(1, 2);
     $obj1 = new ConcretePrototype($demo);
     $obj2 = $obj1->copy();
     var_dump($obj1->getName());
     var_dump($obj2->getName());
     $demo->array = array(3, 4);
     var_dump($obj1->getName());
     var_dump($obj2->getName());
     var_dump($obj1 == $obj2);
 }
Exemple #3
0
abstract class Prototype
{
    private $_id = null;
    public function __construct($id)
    {
        $this->_id = $id;
    }
    public function getId()
    {
        return $this->_id;
    }
    public function __clone()
    {
        //magic function
        $this->_id += 1;
    }
    public function getClone()
    {
        return clone $this;
    }
}
class ConcretePrototype extends Prototype
{
}
$objPrototype = new ConcretePrototype(0);
$objPrototype1 = clone $objPrototype;
echo $objPrototype1->getId() . "\n";
$objPrototype2 = $objPrototype;
echo $objPrototype2->getId() . "\n";
$objPrototype3 = $objPrototype->getClone();
echo $objPrototype3->getId() . "\n";
<?php

interface Prototype
{
    public function copy();
}
class ConcretePrototype implements Prototype
{
    private $_name;
    public function __construct($name)
    {
        $this->_name = $name;
    }
    public function copy()
    {
        return clone $this;
    }
}
class Demo
{
}
// client
$demo = new Demo();
$object1 = new ConcretePrototype($demo);
$object2 = $object1->copy();