[资料]PHP中的clone使用
PHP中的clone使用
官方文档:http://cn2.php.net/__clone
在多数情况下,我们并不需要完全复制一个对象来获得其中属性。但有一个情况下确实需要:如果你有一个 GTK窗口对象,该对象持有窗口相关的资源。你可能会想复制一个新的窗口,保持所有属性与原来的窗口相同, 但必须是一个新的对象(因为如果不是新的对象,那么一个窗口中的改变就会影响到另一个窗口)。还有一种情况: 如果对象A中保存着对象B的引用,当你复制对象A时,你想其中使用的对象不再是对象B而是B的一个副本,那么 你必须得到对象A的一个副本。
对象复制可以通过clone关键字来完成(如果可能,这将调用对象的__clone()方法)。对象中的 __clone()方法不能被直接调用。
Demo 1
<?php class 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
<?php class 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 too print $person2->account->balance; // output: // 210 ?>
申明
非源创博文中的内容均收集自网上,若有侵权之处,请及时联络,我会在第一时间内删除.再次说声抱歉!!!
博文欢迎转载,但请给出原文连接。