本文執行個體講述了PHP對象複製clone用法。分享給大家供大家參考,具體如下:
淺複製:只是複製對象中的非對象非資源資料,即對象中屬性儲存區的是物件類型,則會出現複製不完全
<?phpclass B{ public $val = 10;}class A{ public $val = 20; public $b; public function __construct(){ $this->b = new B(); }}$obj_a = new A();$obj_b = clone $obj_a;$obj_a->val = 30;$obj_a->b->val = 40;var_dump($obj_a);echo '<br>';var_dump($obj_b);
運行結果如下:
object(A)[1] public 'val' => int 30 public 'b' => object(B)[2] public 'val' => int 40 object(A)[3] public 'val' => int 20 public 'b' => object(B)[2] public 'val' => int 40
深複製:一個對象的所有屬性資料都徹底的複製,需要使用魔術方法__clone(),並在裡面實現深度複製
<?phpclass B{ public $val = 10;}class A{ public $val = 20; public $b; public function __construct(){ $this->b = new B(); } public function __clone(){ $this->b = clone $this->b; }}$obj_a = new A();$obj_b = clone $obj_a;$obj_a->val = 30;$obj_a->b->val = 40;var_dump($obj_a);echo '<br>';var_dump($obj_b);
運行結果如下:
object(A)[1] public 'val' => int 30 public 'b' => object(B)[2] public 'val' => int 40 object(A)[3] public 'val' => int 20 public 'b' => object(B)[4] public 'val' => int 10
希望本文所述對大家PHP程式設計有所協助。