__call() 是 PHP 物件導向的核心魔術方法之一:當呼叫不可訪問的方法(不存在、或權限不足)時自動觸發。本文解析其機制、參數結構、實戰應用場景(動態代理、API 客戶端、DSL 建構)。
public function __call(string $name, array $arguments): mixed
$name:被呼叫的方法名(區分大小寫)$arguments:傳遞給方法的參數陣列(數值索引)__callStatic()<?php
class A {
public $name;
public function test1($a) { echo "test1111"; }
public function test2($a) { echo "test2222"; }
// 攔截所有不存在的方法呼叫
public function __call($method, $args) {
echo "類中找不到方法:$method\n";
echo "傳入參數: " . json_encode($args, JSON_UNESCAPED_UNICODE) . "\n";
}
}
$aaa = new A();
$aaa->test(1); // 輸出:類中找不到方法:test / 傳入參數: [1]
$aaa->unknown('a', 'b'); // 輸出:類中找不到方法:unknown / 傳入參數: ["a","b"]
<?php
class ApiClient {
private $baseUrl;
private $httpClient; // GuzzleHttp\Client 或自定義
public function __construct(string $baseUrl) {
$this->baseUrl = rtrim($baseUrl, '/');
$this->httpClient = new \GuzzleHttp\Client();
}
public function __call(string $endpoint, array $args) {
// 規約:方法名 = 端點路徑(底線轉斜線),第一參數 = 陣列參數
$path = str_replace('_', '/', $endpoint);
$params = $args[0] ?? [];
$method = isset($params['_method']) ? strtoupper($params['_method']) : 'GET';
unset($params['_method']);
$url = "{$this->baseUrl}/{$path}";
$options = $method === 'GET' ? ['query' => $params] : ['json' => $params];
try {
$response = $this->httpClient->request($method, $url, $options);
return json_decode($response->getBody()->getContents(), true);
} catch (\GuzzleHttp\Exception\ClientException $e) {
throw new \RuntimeException("API Error {$e->getCode()}: " . $e->getResponse()->getBody());
}
}
}
// 使用:像呼叫本地方法一樣呼叫遠端 API
$api = new ApiClient('https://api.github.com');
$user = $api->users_octocat(); // GET /users/octocat
$repos = $api->users_octocat_repos(); // GET /users/octocat/repos
$create = $api->user_repos(['_method'=>'POST', 'name'=>'new-repo']); // POST /user/repos
<?php
class QueryBuilder {
private $table;
private $wheres = [];
private $selects = ['*'];
private $limit = null;
private $orderBy = null;
public function __construct(string $table) { $this->table = $table; }
// 攔截 whereXxx、orderByXxx、limitXxx 等動態方法
public function __call($method, $args) {
if (preg_match('/^where(.+)/', $method, $m)) {
$column = $this->camelToSnake($m[1]);
$op = '=';
$value = $args[0];
if (count($args) >= 2) { $op = $args[0]; $value = $args[1]; }
$this->wheres[] = compact('column', 'op', 'value');
return $this; // 鏈式呼叫
}
if (preg_match('/^orderBy(.+)/', $method, $m)) {
$this->orderBy = [$this->camelToSnake($m[1]), $args[0] ?? 'ASC'];
return $this;
}
if ($method === 'limit') {
$this->limit = (int)$args[0];
return $this;
}
if ($method === 'get') {
return $this->executeSelect();
}
throw new BadMethodCallException("Unknown method: $method");
}
private function camelToSnake(string $str): string {
return strtolower(preg_replace('/([A-Z])/', '_$1', $str));
}
private function executeSelect(): array {
$sql = "SELECT " . implode(',', $this->selects) . " FROM {$this->table}";
$params = [];
if ($this->wheres) {
$sql .= " WHERE " . implode(' AND ', array_map(fn($w) => "{$w['column']} {$w['op']} ?", $this->wheres));
$params = array_column($this->wheres, 'value');
}
if ($this->orderBy) $sql .= " ORDER BY {$this->orderBy[0]} {$this->orderBy[1]}";
if ($this->limit) $sql .= " LIMIT {$this->limit}";
// 實際執行 PDO...
return ['sql' => $sql, 'params' => $params];
}
}
// 使用
$qb = new QueryBuilder('users');
$result = $qb->whereEmail('test@example.com')
->whereAge('>', 18)
->orderByCreatedAt('DESC')
->limit(10)
->get();
// $result['sql'] = "SELECT * FROM users WHERE email = ? AND age > ? ORDER BY created_at DESC LIMIT 10"
<?php
class ServiceProxy {
private $services = [];
public function register(string $name, object $service): void {
$this->services[$name] = $service;
}
public function __call(string $method, array $args) {
// 規約:serviceName_methodName
foreach ($this->services as $name => $service) {
if (method_exists($service, $method)) {
return $service->$method(...$args);
}
// 支援前綴:user_getProfile -> $services['user']->getProfile()
if (strpos($method, $name . '_') === 0) {
$realMethod = substr($method, strlen($name) + 1);
if (method_exists($service, $realMethod)) {
return $service->$realMethod(...$args);
}
}
}
throw new BadMethodCallException("No service handles method: $method");
}
}
$proxy = new ServiceProxy();
$proxy->register('user', new UserService());
$proxy->register('order', new OrderService());
$proxy->user_getProfile(123); // -> UserService::getProfile(123)
$proxy->order_create(['item'=>'A']); // -> OrderService::create(['item'=>'A'])
| 項目 | 說明 |
|---|---|
| 效能開銷 | 比直接呼叫慢 ~2-3 倍(魔術方法查找機制),高頻熱路徑避免使用 |
| IDE 支援 | 無法自動補全,建議加 @method 註解 |
| 繼承行為 | 子類別未重寫 __call 會繼承父類別邏輯 |
| 遞迴風險 | __call 內部呼叫同樣不存在的方法會無限遞迴,需防護 |
| 介面契約 | 動態方法無法滿足介面定義,需謹慎設計 |
$name、$arguments,拋出明確異常@method PHPDoc 讓 IDE 支援提示__call() 是 PHP 動態特性的集中體現,善用可大幅減少樣板代碼,濫用則導致難以追蹤的「魔法」代碼。