本文實例講述了PHP物件克隆clone用法。分享給大家供大家參考,如下:
淺克隆:只是克隆對像中的非對象非資源數據,即對像中屬性存儲的是對象類型,則會出現克隆不完全
<?php class 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
<?php class 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程式設計有所幫助。
更多PHP物件克隆clone用法範例相關文章請關注PHP中文網!