php中对象的引用、浅复制、深复制 发表于 2017-07-14 概念引用: 对象之间的等号赋值是引用赋值,两者是同一个资源浅复制: 值赋值。所有的引用属性(如对象属性)仍然是一个指向原来变量的引用深复制: 所有引用属性指向复制过来的新对象 测试引用1234567891011121314151617class A{ public $obj; public $name='A'; public function __construct(){ $this->obj = new B(); }}class B{ public $name='B';}$a = new A();$b = $a;var_dump($a,$b); //引用 两者完全相同 1234567891011121314151617181920//结果class A#1 (2) { public $obj => class B#2 (1) { public $name => string(1) "B" } public $name => string(1) "A"}class A#1 (2) { public $obj => class B#2 (1) { public $name => string(1) "B" } public $name => string(1) "A"} 浅复制12$b = clone $a;var_dump($a,$b); //浅复制 $b中的obj依旧指向$a中的obj 1234567891011121314151617181920//结果class A#1 (2) { public $obj => class B#2 (1) { public $name => string(1) "B" } public $name => string(1) "A"}class A#3 (2) { public $obj => class B#2 (1) { public $name => string(1) "B" } public $name => string(1) "A"} 深复制1234567891011121314151617181920class A{ public $obj; public $name='A'; public function __construct(){ $this->obj = new B(); } public function __clone(){ $this->obj = new B(); }}class B{ public $name='B';}$a = new A();$b = clone $a;var_dump($a,$b); //深复制 $b中的obj依旧指向$a中的obj 1234567891011121314151617181920//结果class A#1 (2) { public $obj => class B#2 (1) { public $name => string(1) "B" } public $name => string(1) "A"}class A#3 (2) { public $obj => class B#4 (1) { public $name => string(1) "B" } public $name => string(1) "A"}