從php5以後的版本,類別就可以使用魔術方法了。 php規定以兩個底線(__)開頭的方法都保留為魔術方法,所以建議大家函數名最好不用__開 頭,除非是為了重載已有的魔術方法。
目前php已有的魔術方法有 __construct,__destruct,__call,__get,__set,__isset,__unset,__sleep,__wakeup,__toString,__set_state 和 __clone。
下面我們來看看兩個魔術方法:__clone()和__toString().
__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; ?>
結果如下
<span>1</span> ------------------------------------------------------------------------------------<span> I Love You So Much! </span>------------------------------------------------------------------------------------<span> no zuo no die /*要不是有__clone()这个魔术方法,这边的结果应该是2*/ </span>------------------------------------------------------------------------------------<span> I Love You So Much!</span>
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 <span>Object</span><span>: MyCloneable </span><span>Object</span><span> ( [object1] </span>=> SubObject <span>Object</span><span> ( [instance] </span>=> <span>1</span><span> ) [object2] </span>=> SubObject <span>Object</span><span> ( [instance] </span>=> <span>2</span><span> ) ) Cloned </span><span>Object</span><span>: MyCloneable </span><span>Object</span><span> ( [object1] </span>=> SubObject <span>Object</span><span> ( [instance] </span>=> <span>3 <span>/*可能这里比较难以理解,其实就是$obj2当克隆的时候将最后的instance为2的结果克隆,并且再执行SubObject::__clone方法*/</span></span><span> ) [object2] </span>=> SubObject <span>Object</span><span> ( [instance] </span>=> <span>2</span><span> ) )</span>
__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
以上就介紹了PHP 魔術方法: __clone __toString,包括了PHP魔術方法方面的內容,希望對PHP教程有興趣的朋友有所幫助。