这种模式主要是复制对象。有点类似单例。但又不相同。 代码如下
|
01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
|
<?php /** * 原型接口 */interface IPrototype{ public function copy($type);}/** * 原型类 */class Prototype implements IPrototype{ public $name;//测试用的 public function __construct($name) { $this->name = $name; } public function copy($type = 1)//复制本身 { return $type == 1 ? $this->copy1() : $this->copy2(); } private function copy1()//浅复制 { return clone $this; } private function copy2()//深度复制 { return unserialize(serialize($this)); }}class Test//测试的一个类。注意看打印的类的 id{ public $test1 = ‘test1‘;}$prototype1 = new Prototype(new Test());var_dump($prototype1); //$prototype1 资源号是1 Test是2echo ‘<hr>‘;$prototype2 = $prototype1->copy(1);//浅复制var_dump($prototype2);//$prototype2 资源号是3 Test仍然是2echo ‘<hr>‘;$prototype3 = $prototype1->copy(0);//深复制var_dump($prototype3);//$prototype3 资源号是4 test是5?> |
结果如下
object(Prototype)#1 (1) { ["name"]=> object(Test)#2 (1) { ["test1"]=> string(5) "test1" } }
object(Prototype)#3 (1) { ["name"]=> object(Test)#2 (1) { ["test1"]=> string(5) "test1" } }
object(Prototype)#4 (1) { ["name"]=> object(Test)#5 (1) { ["test1"]=> string(5) "test1" } }
注意结果中的资源号 分别是
#1 #2
#3 #2
#4 #5
浅复制时,变量的资源号不变。 深复制时,是把成员从新创建的。
原文:http://www.cnblogs.com/ghjbk/p/6670238.html