PHP 提供豐富的執行期反射能力,讓你能動態檢查類別、函數、方法是否存在、取得名稱、參數、屬性等中繼資料。本文系統整理 7 大核心檢查函數、3 大魔術常數、反射 API 實戰用法,並說明動態呼叫的效能與安全考量。
| 函數 | 用途 | 回傳值 | 自動載入觸發 | 適用對象 | |
|---|---|---|---|---|---|
function_exists() | 檢查函數是否已定義 | bool | 否 | 函數 (含內建、使用者定義) | |
class_exists() | 檢查類別/介面/特徵是否已定義 | bool | 是 (預設 $autoload=true) | 類別、介面、Trait | |
interface_exists() | 檢查介面是否已定義 | bool | 是 | 介面 | |
trait_exists() | 檢查 Trait 是否已定義 | bool | 是 | Trait | |
method_exists() | 檢查類別/物件是否有指定方法 | bool | 是 (若類別未載入) | 物件實例、類別名稱 | |
property_exists() | 檢查類別/物件是否有指定屬性 | bool | 是 | 物件實例、類別名稱 | |
is_callable() | 檢查變數是否為合法可呼叫結構 | bool | 否 (不觸發自動載入) | 函數名、靜態方法、物件方法、閉包、invokable 物件 |
<?php
class Foo {
public function bar() {}
public static function baz() {}
}
$obj = new Foo();
// class_exists: 檢查類別定義存在 (觸發 autoload)
var_dump(class_exists('Foo')); // true
var_dump(class_exists('NonExist')); // false
// method_exists: 檢查方法存在 (需類別已載入)
var_dump(method_exists($obj, 'bar')); // true
var_dump(method_exists('Foo', 'baz')); // true (靜態方法)
var_dump(method_exists('Foo', 'none')); // false
// is_callable: 檢查「可被呼叫」 (不觸發 autoload,更安全)
var_dump(is_callable('Foo::baz')); // true (靜態方法字串)
var_dump(is_callable([$obj, 'bar'])); // true (物件方法)
var_dump(is_callable('non_exist_func')); // false (不觸發 autoload)
var_dump(is_callable('NonExist::method'));// false (不觸發 autoload)
// 關鍵差異:is_callable 不會觸發自動載入,適合「檢查後才決定是否載入」場景
if (is_callable('HeavyClass::heavyMethod')) {
// 這裡才 require 或 autoload
}
| 常數 | 含義 | 範例輸出 | 注意事項 |
|---|---|---|---|
__FUNCTION__ | 當前函數名稱 (區分大小寫) | myFunction | 全域函數/方法內有效;PHP 4 為小寫 |
__METHOD__ | 當前類別方法名稱 (含類別名) | MyClass::myMethod | PHP 5.0+;靜態/非靜態皆適用 |
__CLASS__ | 當前類別名稱 (含命名空間) | App\Models\User | PHP 4.3+;Trait 中表使用該 Trait 的類別 |
__TRAIT__ | 當前 Trait 名稱 | App\Traits\Loggable | PHP 5.4+ |
__NAMESPACE__ | 當前命名空間 | App\Controllers | PHP 5.3+ |
__FILE__ | 當前檔案完整路徑 (已解析符號連結) | /var/www/app/Http/Controllers/UserController.php | 包含檔中表被包含檔路徑 |
__DIR__ | 當前檔案目錄 (等同 dirname(__FILE__)) | /var/www/app/Http/Controllers | PHP 5.3+ |
__LINE__ | 當前行號 | 42 | 除錯、日誌常用 |
<?php
// Plugin 介面
interface PluginInterface {
public function getName(): string;
public function execute(array $params): mixed;
}
// 動態載入器
class PluginLoader {
private string $pluginDir;
private array $loaded = [];
public function __construct(string $pluginDir) {
$this->pluginDir = $pluginDir;
}
public function load(string $name): ?PluginInterface {
if (isset($this->loaded[$name])) return $this->loaded[$name];
$file = $this->pluginDir . '/' . $name . '/' . $name . '.php';
if (!is_file($file)) return null;
// 安全檢查:檔案內是否定義了符合介面的類別
$code = file_get_contents($file);
if (!preg_match('/class\s+(\w+)\s+implements\s+PluginInterface/', $code)) {
throw new RuntimeException("Plugin $name 不符合介面規範");
}
require_once $file;
// 掃描檔案中定義的類別
$classes = get_declared_classes();
$newClasses = array_diff($classes, get_declared_classes()); // 邏輯需調整,這裡示意
// 實際做法:約定類別名 = PluginName + 'Plugin'
$className = ucfirst($name) . 'Plugin';
if (!class_exists($className)) {
throw new RuntimeException("找不到類別 $className");
}
if (!is_subclass_of($className, PluginInterface::class)) {
throw new RuntimeException("$className 未實作 PluginInterface");
}
$instance = new $className();
$this->loaded[$name] = $instance;
return $instance;
}
public function call(string $plugin, string $method, array $args = []): mixed {
$instance = $this->load($plugin);
if (!$instance) throw new RuntimeException("Plugin $plugin 不存在");
if (!method_exists($instance, $method)) {
throw new BadMethodCallException("Method $method 不存在");
}
return $instance->$method(...$args);
}
}
// 使用
$loader = new PluginLoader(__DIR__ . '/plugins');
$result = $loader->call('image', 'resize', ['width' => 800, 'height' => 600]);
<?php
#[Attribute(Attribute::TARGET_METHOD)]
class Route {
public function __construct(
public string $method,
public string $path,
public array $middleware = []
) {}
}
class UserController {
#[Route('GET', '/users')]
public function index() { /* ... */ }
#[Route('POST', '/users', ['auth', 'validate'])]
public function store() { /* ... */ }
}
// 掃描路由屬性
$refClass = new ReflectionClass(UserController::class);
foreach ($refClass->getMethods() as $refMethod) {
$attrs = $refMethod->getAttributes(Route::class);
foreach ($attrs as $attr) {
$route = $attr->newInstance();
echo "{$route->method} {$route->path} -> {$refMethod->name}()\n";
// 輸出: GET /users -> index()
// POST /users -> store()
}
}
// 參數型別提示檢查 (用於自動注入)
$params = $refMethod->getParameters();
foreach ($params as $param) {
$type = $param->getType();
if ($type instanceof ReflectionNamedType && !$type->isBuiltin()) {
$className = $type->getName(); // 取得型別類別名
// 從容器解析...
}
}
is_callable:不觸發 autoload,適合條件式載入。classmap_authoritative 或 optimize-autoloader 將類別對應編譯成陣列,class_exists 變極快。$obj->$method() 或 $class::$method() 前,務必白名單驗證方法名,防 RCE。method_exists 回傳 true 但呼叫失敗private/protected、需特定參數、或被 __call 魔術方法處理。用 ReflectionMethod::isPublic() 進一步檢查。class_exists('Parent') 在子類別中為 trueclass_exists 檢查類別定義存在,繼承鏈不影響。class_exists('User') 在命名空間 App 中會找 App\User;跨命名空間需用完整名稱 \App\Models\User 或 User::class。function_exists 不支援命名空間函數function_exists('App\Helpers\helper_func')。掌握 PHP 反射與存在性檢查,能構建靈活的插件系統、自動路由、依賴注入容器、序列化器等核心基礎設施。記住:編譯期魔術常數最快、is_callable 最安全、Reflection 最強大但最慢,根據場景選擇正確工具!