Loading... # PHP 对象克隆(浅拷贝和深拷贝) --- ## 1. 对象是通过引用传递的 ```php class My_class{ private $color; } $obj = new My_class; $obj->color = 'red'; $obj2 = $obj; $obj2->color = 'blue'; echo $obj->color . "\n"; echo $obj2->color; //输出 // blue // blue ``` ## 2. 同过 clone 克隆对象是浅拷贝 ```php class My_class{ private $color; } $obj = new My_class; $obj1= clone($obj); $obj->color = 'red'; $obj1->color = 'blue'; echo $obj->color . "\n"; echo $obj1->color; //输出: // red // blue ``` ## 3. 通过 __clone 深拷贝复制对象 > 使用 clone 克隆对象,对象指向的是两个不同的地址, > 但是如果对象里面有成员变量是引用的话 > 那么在其中一个对象修改这个引用变量,都是改变他的值 > 比如 PHP 类里面依赖注入的时候,很多 private 的对象 a) 普通情况 ```php class My_class{ private $color; } $color = 'red'; $obj1 = new My_class(); $obj1->color = &$color; $obj2 = clone obj1; $obj2->color = 'blue'; echo $obj1->color . "\n"; echo $obj2->color; // 结果 // blue // blue ``` ### b) 使用深拷贝 ```php class My_class{ private $color; public function __clone(){ $this->color = clone $this->color; } } $color = 'red'; $obj1 = new My_class(); $obj1->color = &$color; $obj2 = clone obj1; $obj2->color = 'blue'; echo $obj1->color . "\n"; echo $obj2->color; // 结果 // red // blue ``` © Allow specification reprint Support Appreciate the author AliPayWeChat Like If you think my article is useful to you, please feel free to appreciate