PHP 中以雙底線 __ 開頭的方法稱為魔術方法,會在特定生命週期或操作觸發時自動被呼叫。掌握它們能實現优雅的物件導向設計模式。
| 方法 | 觸發時機 | 常見用途 |
|---|---|---|
__construct() | new 實例化 | 初始化屬性、資源連線 |
__destruct() | 物件銷毀/腳本結束 | 釋放資源、關閉連線、寫日誌 |
__call() | 呼叫不可訪問實例方法 | 動態方法代理、錯誤友善處理 |
__callStatic() | 靜態呼叫不可訪問方法 | 靜態代理、流式介面 |
__get() | 讀取不可訪問屬性 | 屬性存取控制、虛擬屬性、延遲載入 |
__set() | 寫入不可訪問屬性 | 資料驗證、唯讀保護、觸發事件 |
__isset() | isset()/empty() 檢查不可訪問屬性 | 隱藏屬性存在性判斷 |
__unset() | unset() 不可訪問屬性 | 軟刪除、快取清理 |
__sleep() | serialize() 序列化前 | 清理資源、指定序列化屬性白名單 |
__wakeup() | unserialize() 反序列化後 | 重建連線、初始化資源 |
__toString() | 物件當字串使用 | 日誌輸出、API 回應、除錯顯示 |
__invoke() | 物件當函數呼叫 $obj() | 可呼叫物件、策略模式、閉包替代 |
__set_state() | var_export() 匯出類別 | 自定義匯出格式、單例模式還原 |
__clone() | clone 物件後 | 深拷貝、資源重新建立、ID 重置 |
__autoload() | 類別未定義時嘗試載入 | 舊版自動載入(已棄用,改用 spl_autoload_register) |
__debugInfo() | var_dump()/print_r() 除錯輸出 | 隱藏敏感屬性、自訂除錯視圖 |
<?php
class User {
private $data = [];
private $allowed = ['name', 'email', 'age'];
public function __get($key) {
if (in_array($key, $this->allowed)) {
return $this->data[$key] ?? null;
}
throw new Exception("屬性 {$key} 不存在或不可讀");
}
public function __set($key, $value) {
if (!in_array($key, $this->allowed)) {
throw new Exception("屬性 {$key} 不允許寫入");
}
if ($key === 'age' && ($value < 0 || $value > 150)) {
throw new Exception('年齡必須 0-150');
}
$this->data[$key] = $value;
}
public function __isset($key) {
return in_array($key, $this->allowed) && isset($this->data[$key]);
}
public function __unset($key) {
if (in_array($key, $this->allowed)) {
unset($this->data[$key]);
}
}
}
$user = new User();
$user->name = '小明'; // __set
echo $user->name; // __get -> 小明
echo isset($user->email); // __isset -> false
unset($user->name); // __unset
?>
<?php
class ApiClient {
private $apiKey;
private $httpClient; // Guzzle 等資源,不可序列化
private $cache = [];
public function __construct(string $apiKey) {
$this->apiKey = $apiKey;
$this->httpClient = new GuzzleHttp\Client();
}
public function __sleep(): array {
// 僅序列化 apiKey 與 cache,排除 httpClient
$this->cache = $this->getHotCache(); // 序列化前同步熱點快取
return ['apiKey', 'cache'];
}
public function __wakeup(): void {
// 反序列化後重建連線
$this->httpClient = new GuzzleHttp\Client();
$this->warmUpCache(); // 預熱快取
}
}
?>
<?php
class RequestHandler {
private $middlewares = [];
public function addMiddleware(callable $mw) {
$this->middlewares[] = $mw;
}
public function __invoke(Request $request): Response {
$response = new Response();
foreach ($this->middlewares as $mw) {
$response = $mw($request, $response);
if ($response->isTerminated()) break;
}
return $response;
}
}
$handler = new RequestHandler();
$handler->addMiddleware(fn($req, $res) => $res->setHeader('X-Powered-By', 'PHP'));
$response = $handler($request); // 直接像函數一樣呼叫
?>
<?php
class User {
private $id;
private $passwordHash;
private $email;
public function __debugInfo(): array {
return [
'id' => $this->id,
'email' => $this->email,
// 故意隱藏 passwordHash
];
}
}
$user = new User(1, 'hash...', 'test@example.com');
var_dump($user);
// 輸出僅含 id、email,無 passwordHash
?>
<?php
class Order {
public $id;
public $items; // OrderItem 物件陣列
public $createdAt;
public function __clone() {
$this->id = 0; // 新訂單需重新生成 ID
$this->createdAt = new DateTime();
// 深拷貝 items 陣列
foreach ($this->items as $key => $item) {
$this->items[$key] = clone $item;
}
}
}
?>
spl_autoload_register() 或 Composer 自動載入__construct()@property、@method 註解讓 IDE 支援自動完成__get/__set 比直接存取慢,熱點路徑避免過度使用__destruct/__wakeup 中切勿拋出異常16 個魔術方法構成 PHP 物件導向的「隱形骨架」。核心常用者:__construct/__destruct(生命週期)、__get/__set/__isset/__unset(屬性代理)、__sleep/__wakeup(序列化)、__toString/__invoke/__debugInfo(介面行為)、__clone(拷貝控制)。善用它們能寫出更具表達力、封裝性更強的程式碼,但濫用會導致隱式行為難以追蹤,請在架構層面制定使用規範。