PHP 允許將函數名稱以字串儲存於變數,再透過變數動態呼叫,適用於插件架構、回調處理、路由分發等場景。
<?php
function sayHello() {
echo "Hello
";
}
$funcName = 'sayHello';
$funcName(); // 輸出 Hello
// 帶參數
function greet($name) {
echo "Hello, $name!
";
}
$func = 'greet';
$func('World'); // 輸出 Hello, World!
?>
<?php
class Service {
public function process($data) {
return strtoupper($data);
}
public static function staticMethod() {
return 'static called';
}
}
$obj = new Service();
$method = 'process';
echo $obj->$method('test'); // TEST
// 靜態方法
$class = 'Service';
$staticMethod = 'staticMethod';
echo $class::$staticMethod(); // static called
?>
<?php
$routes = [
'home' => 'Controller\Home::index',
'user' => 'Controller\User::profile',
'api' => function() { echo 'API endpoint'; },
];
$action = $_GET['action'] ?? 'home';
$handler = $routes[$action] ?? function() { http_response_code(404); echo 'Not Found'; };
if (is_string($handler) && strpos($handler, '::')) {
[$class, $method] = explode('::', $handler);
(new $class())->$method();
} elseif (is_callable($handler)) {
$handler();
}
?>
$_GET['func'] 作為函數名執行is_callable() 檢查後再呼叫eval() 或 create_function()| 函式 | 用途 |
|---|---|
| is_callable() | 檢查變數是否可作為函數呼叫 |
| call_user_func() | 呼叫回調函數,支援參數傳遞 |
| call_user_func_array() | 以陣列形式傳遞參數呼叫回調 |
| function_exists() | 檢查函數是否已定義 |
| method_exists() | 檢查類別方法是否存在 |