php 魔術方法_PHP教程

來源:互聯網
上載者:User
PHP5.0後,php物件導向提成更多方法,使得php更加的強大!!
一些在PHP叫魔術方法的函數,在這裡介紹一下:其實在一般的應用中,我們都需要用到他們!!

1.__construct() 當執行個體化一個對象的時候,這個對象的這個方法首先被調用。
Java代碼
class Test { function __construct() { echo "before"; } } $t = new Test();
class Test { function __construct() { echo "before"; } } $t = new Test();
輸出是:
start
我們知道php5物件模型 和類名相同的函數是類的建構函式,那麼如果我們同時定義建構函式和__construct()方法的話,php5會預設調用建構函式而不會調用__construct()函數,所以__construct()作為類的預設的建構函式
2.__destruct() 當刪除一個對象或對象操作終止的時候,調用該方法。
Java代碼
class Test { function __destruct() { echo "end"; } } $t = new Test();將會輸出end
class Test { function __destruct() { echo "end"; } } $t = new Test();將會輸出end
我們就可以在對象操作結束的時候進行釋放資源之類的操作
3.__get() 當試圖讀取一個並不存在的屬性的時候被調用。

如果試圖讀取一個對象並不存在的屬性的時候,PHP就會給出錯誤資訊。如果在類裡添加__get方法,並且我們可以用這個函數實作類別似java中反射的各種操作。
Java代碼
class Test { public function __get($key) { echo $key . " 不存在"; } } $t = new Test(); echo $t->name; 就會輸出:name 不存在
class Test { public function __get($key) { echo $key . " 不存在"; } } $t = new Test(); echo $t->name; 就會輸出:name 不存在
4.__set() 當試圖向一個並不存在的屬性寫入值的時候被調用。
Java代碼
class Test { public function __set($key,$value) { echo '對'.$key . "附值".$value; } } $t = new Test(); $t->name = "aninggo"; 就會輸出:對 name 附值 aninggo
class Test { public function __set($key,$value) { echo '對'.$key . "附值".$value; } } $t = new Test(); $t->name = "aninggo"; 就會輸出:對 name 附值 aninggo

5.__call() 當試圖調用一個對象並不存在的方法時,調用該方法。
Java代碼
class Test { public function __call($Key, $Args) { echo "您要調用的 {$Key} 方法不存在。你傳入的參數是:" . print_r($Args, true); } } $t = new Test(); $t->getName(aning,go);
class Test { public function __call($Key, $Args) { echo "您要調用的 {$Key} 方法不存在。你傳入的參數是:" . print_r($Args, true); } } $t = new Test(); $t->getName(aning,go);
程式將會輸出:
Java代碼
您要調用的 getName 方法不存在。參數是:Array
(
[0] => aning
[1] => go
)
您要調用的 getName 方法不存在。參數是:Array
(
[0] => aning
[1] => go
)
6.__toString() 當列印一個對象的時候被調用

這個方法類似於java的toString方法,當我們直接列印對象的時候回調用這個函數
class Test { public function __toString() { return "列印 Test"; } } $t = new Test(); echo $t;
運行echo $t;的時候,就會調用$t->__toString();從而輸出
列印 Test
7.__clone() 當對象被複製時,被調用

class Test { public function __clone() { echo "我被複製了!"; } }$t = new Test(); $t1 = clone $t;程式輸出:我被複製了!

原文轉自指令碼之家《php 魔術方法使用說明》

http://www.bkjia.com/PHPjc/780019.htmlwww.bkjia.comtruehttp://www.bkjia.com/PHPjc/780019.htmlTechArticlePHP5.0後,php物件導向提成更多方法,使得php更加的強大!! 一些在PHP叫魔術方法的函數,在這裡介紹一下:其實在一般的應用中,我們都需...

  • 聯繫我們

    該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

    如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.