文章目錄
PHP中的clone使用
官方文檔:http://cn2.php.net/__clone
在多數情況下,我們並不需要完全複製一個對象來獲得其中屬性。但有一個情況下確實需要:如果你有一個 GTK視窗對象,該對象持有視窗相關的資源。你可能會想複製一個新的視窗,保持所有屬性與原來的視窗相同, 但必須是一個新的對象(因為如果不是新的對象,那麼一個視窗中的改變就會影響到另一個視窗)。還有一種情況: 如果對象A中儲存著對象B的引用,當你複製對象A時,你想其中使用的對象不再是對象B而是B的一個副本,那麼 你必須得到對象A的一個副本。
對象複製可以通過clone關鍵字來完成(如果可能,這將調用對象的__clone()方法)。對象中的 __clone()方法不能被直接調用。
Demo 1
<?phpclass Person { private $name; private $age; private $id; function __construct( $name, $age ) { $this->name = $name; $this->age = $age; } function setId( $id ) { $this->id = $id; } function __clone() { $this->id = 0; }}print "<pre>";$person = new Person( "bob", 44 );$person->setId( 343 );$person2 = clone $person;print_r( $person );print_r( $person2 );print "</pre>";?>
Demo 2
<?phpclass Account { public $balance; function __construct( $balance ) { $this->balance = $balance; }}class Person { private $name; private $age; private $id; public $account; function __construct( $name, $age, Account $account ) { $this->name = $name; $this->age = $age; $this->account = $account; } function setId( $id ) { $this->id = $id; } function __clone() { $this->id = 0; }}$person = new Person( "bob", 44, new Account( 200 ) );$person->setId( 343 );$person2 = clone $person;// give $person some money$person->account->balance += 10;// $person2 sees the credit tooprint $person2->account->balance;// output:// 210?>