__clone() - 當對象克隆的時候自動加載此方法
__toString() - 當對象需要echo打印輸出的時候自動加載此方法
__clone()
<?php class example{ public static $pa; public $pb; public function __construct(){ $this->pb = ++self::$pa; } public function __clone(){ $this->pb = 'no zuo no die'; } } $a = new example; $b = new example; $c = clone $b; $b->pb = 'I Love You So Much!'; echo $a->pb; echo '<hr/>'; echo $b->pb; echo '<hr/>'; echo $c->pb; echo '<hr/>'; echo $b->pb; ?>
結果如下
1 ------------------------------------------------------------------------------------ I Love You So Much! ------------------------------------------------------------------------------------ no zuo no die /*要不是有__clone()這個魔術方法,這邊的結果應該是2*/ ------------------------------------------------------------------------------------ I Love You So Much!
php手冊給了我們一個例子有些難以看懂,如下
<?php class SubObject { static $instances = 0; public $instance; public function __construct() { $this->instance = ++self::$instances; } public function __clone() { $this->instance = ++self::$instances; } } class MyCloneable { public $object1; public $object2; function __clone() { // 強制復制一份this->object, 否則仍然指向同一個對象 $this->object1 = clone $this->object1; } } $obj = new MyCloneable(); $obj->object1 = new SubObject(); $obj->object2 = new SubObject(); $obj2 = clone $obj; print("Original Object:\n"); print_r($obj); print("Cloned Object:\n"); print_r($obj2); ?>
最後的結果
Original Object: MyCloneable Object ( [object1] => SubObject Object ( [instance] => 1 ) [object2] => SubObject Object ( [instance] => 2 ) ) Cloned Object: MyCloneable Object ( [object1] => SubObject Object ( [instance] => 3 /*可能這裡比較難以理解,其實就是$obj2當克隆的時候將最後的instance為2的結果克隆,並且再執行SubObject::__clone方法*/ ) [object2] => SubObject Object ( [instance] => 2 ) )
__toString()
<?php // Declare a simple class class TestClass { public $foo; public function __construct($foo) { $this->foo = $foo; } public function __toString() { return $this->foo; } } $class = new TestClass('Hello'); echo $class; ?>
結果
Hello