PHP 5 起引入魔術方法,讓類別在特定生命週期自動觸發對應行為,大幅增強物件導向能力。
實例化物件時優先呼叫。若同時定義同名方法與 __construct(),PHP 5 預設呼叫 __construct()。
class Test { public function __construct() { echo "before"; } }
$t = new Test(); // 輸出 before
物件銷毀或腳本結束時呼叫,適合釋放資源、關閉連線。
class Test { public function __destruct() { echo "end"; } }
$t = new Test(); // 輸出 end
嘗試讀取不存在或不可見的屬性時觸發,可實作類似反射的動態屬性存取。
class Test { public function __get($key) { echo "$key 不存在"; } }
$t = new Test(); echo $t->name; // 輸出 name 不存在
嘗試對不存在或不可見屬性賦值時觸發。
class Test { public function __set($key,$value) { echo "對 $key 附值 $value"; } }
$t = new Test(); $t->name = "aninggo"; // 輸出 對 name 附值 aninggo
呼叫不存在或不可見的方法時觸發,參數為方法名與引數陣列。
class Test {
public function __call($Key, $Args) {
echo "您要呼叫的 {$Key} 方法不存在。參數:" . print_r($Args, true);
}
}
$t = new Test(); $t->getName('aning','go');
直接 echo $obj 時自動呼叫,必須回傳字串。
class Test { public function __toString() { return "列印 Test"; } }
$t = new Test(); echo $t; // 輸出 列印 Test
clone 關鍵字建立副本時觸發,可在其中處理深層複製邏輯。
class Test { public function __clone() { echo "我被複製了!"; } }
$t = new Test(); $t1 = clone $t; // 輸出 我被複製了!
善用這些魔術方法,能讓程式碼更符合物件導向設計模式,提升彈性與可維護性。