用AI赚第一桶💰低成本搭建一套AI赚钱工具,源码可二开。 广告
[TOC] ## 概述 使用示例: PHP 中提供立即可用的原型模式。 你可以使用 clone关键字创建一个对象的完整副本。 如果想要某个类支持克隆功能, 你需要实现 __clone方法 ## 示例 ### 概念示例 <details> <summary>main.php</summary> ``` <?php 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 = 245; $p1->component = new \DateTime(); $p1->circularReference = new ComponentWithBackReference($p1); $p2 = clone $p1; if ($p1->primitive === $p2->primitive) { echo "primitive 相等\n"; } else { echo "Primitive 不相等\n"; } if ($p1->component === $p2->component) { echo "component 相等\n"; } else { echo "component 不相等\n"; } if ($p1->circularReference === $p2->circularReference) { echo "circularReference 相等\n"; } else { echo "circularReference 不相等\n"; } if ($p1->circularReference->prototype === $p2->circularReference->prototype) { echo "prototype 相等\n"; } else { echo "prototype 不相等\n"; } } clientCode(); ``` </details> <br /> ### 真是示例 <details> <summary>main.php</summary> ``` <?php class Page { private $title; private $body; private $author; private $comments = []; private $date; // +100 private fields. public function __construct(string $title, string $body, Author $author) { $this->title = $title; $this->body = $body; $this->author = $author; $this->author->addToPage($this); $this->date = new \DateTime(); } public function addComment(string $comment): void { $this->comments[] = $comment; } public function __clone() { $this->title = "Copy of " . $this->title; $this->author->addToPage($this); $this->comments = []; $this->date = new \DateTime(); } } class Author { private $name; /** * @var Page[] */ private $pages = []; public function __construct(string $name) { $this->name = $name; } public function addToPage(Page $page): void { $this->pages[] = $page; } } function clientCode() { $author = new Author("John Smith"); $page = new Page("Tip of the day", "Keep calm and carry on.", $author); // ... $page->addComment("Nice tip, thanks!"); // ... $draft = clone $page; print_r($draft); } clientCode(); ``` </details> <br />