首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 網頁程式設計 >> PHP 程式設計 >> PHP 相關知識

PHP 動態函數調用技巧:透過字串變數呼叫函數

     編輯:PHP 相關知識

PHP 動態函數調用技巧:透過字串變數呼叫函數

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()

相關函式

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved
函式用途
is_callable()檢查變數是否可作為函數呼叫
call_user_func()呼叫回調函數,支援參數傳遞
call_user_func_array()以陣列形式傳遞參數呼叫回調
function_exists()檢查函數是否已定義
method_exists()檢查類別方法是否存在