在物件導向開發中,若呼叫物件不存在的方法,PHP 會拋出 Fatal Error 並中斷程式執行。這在動態方法呼叫、代理模式或 API 封裝等場景下極為不便。__call() 魔術方法 正是為了解決此問題而設計:當呼叫不可存取的方法時自動觸發,讓程式能優雅地處理錯誤並繼續執行。
public function __call(string $name, array $arguments): mixed
<?php
class Test {}
$test = new Test();
$test->demo("one", "two", "three"); // Fatal Error: Call to undefined method Test::demo()
echo "這行不會執行"; // 程式已中斷
?>
<?php
class Test {
public function __call($function_name, $args) {
echo "你所呼叫的函數:$function_name (參數:";
print_r($args);
echo ") 不存在!<br>";
}
}
$test = new Test();
$test->demo("one", "two", "three"); // 自動觸發 __call()
echo "this is a test<br>"; // 程式繼續執行
?>
你所呼叫的函數:demo (參數:Array ( [0] => one [1] => two [2] => three ) ) 不存在!
this is a test
<?php
class Model {
protected $data = [];
public function __call($method, $args) {
// 處理 getFieldName() / setFieldName() 動態存取
if (preg_match('/^(get|set)([A-Z]\w+)$/', $method, $matches)) {
$field = lcfirst($matches[2]);
if ($matches[1] === 'get') {
return $this->data[$field] ?? null;
} else {
$this->data[$field] = $args[0] ?? null;
return $this; // 支援鏈式呼叫
}
}
throw new BadMethodCallException("Method $method does not exist");
}
}
$user = new Model();
$user->setName('張三')->setEmail('zhang@example.com');
echo $user->getName(); // 張三
?>
<?php
class ApiClient {
private $baseUrl;
public function __construct($baseUrl) {
$this->baseUrl = $baseUrl;
}
public function __call($endpoint, $args) {
$params = $args[0] ?? [];
// 動態建構 API 請求
return $this->request($endpoint, $params);
}
private function request($endpoint, $params) {
// 實際 HTTP 請求邏輯
return "Calling API: $endpoint with " . json_encode($params);
}
}
$api = new ApiClient('https://api.example.com');
echo $api->getUser(['id' => 123]); // 呼叫不存在的 getUser() 自動轉向 API 端點
?>
BadMethodCallException 而非單純輸出訊息__callStatic() 處理__call() 是 PHP 物件導向的強大特性,能實現動態方法呼叫、優雅錯誤處理、代理模式等進階架構。善用此特性可讓程式碼更具彈性,但需注意可讀性與維護性的平衡。