@gilbert
To implement the Prototype design pattern in PHP, you can follow these steps:
1 2 3 4 |
abstract class Prototype { abstract public function clone(); } |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
class ConcretePrototype extends Prototype { private $property; public function __construct($property) { $this->property = $property; } public function clone() { return new ConcretePrototype($this->property); } } |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
class Client { private $prototype; public function __construct(Prototype $prototype) { $this->prototype = $prototype; } public function createObject() { return $this->prototype->clone(); } } |
1 2 3 4 |
$prototype = new ConcretePrototype('default value'); $client = new Client($prototype); $newObject = $client->createObject(); |
In this example, $newObject
will be a new instance of the ConcretePrototype
class, with the same property value as the original prototype. You can then modify the new object's properties without affecting the original prototype.