動態函數呼叫是實現插件系統、策略模式、路由分發、延遲執行的核心技術。本文深入解析 `call_user_func`、`call_user_func_array` 與相關函數 `func_get_args`、`func_num_args` 的用法、差異與進階應用。
| 函數 | 參數傳遞方式 | 適用場景 | 效能 |
|---|---|---|---|
call_user_func($cb, $arg1, $arg2...) | 列舉參數 | 參數固定、數量少、靜態呼叫 | 略快 |
call_user_func_array($cb, [$arg1, $arg2...]) | 陣列參數 | 參數動態、數量不定、參數來自陣列/JSON | 略慢(陣列解包) |
$cb(...$args) (PHP 5.6+) | 解包運算子 | 現代寫法、可讀性最佳、JIT 優化友善 | 最快 |
<?php
function greet($name, $suffix = '!') {
echo "Hello, $name$suffix\n";
}
// call_user_func
call_user_func('greet', 'World'); // Hello, World!
call_user_func('greet', 'PHP', '~'); // Hello, PHP~
// call_user_func_array
call_user_func_array('greet', ['Laravel']); // Hello, Laravel!
call_user_func_array('greet', ['Symfony', '★']); // Hello, Symfony★
// 現代寫法 (PHP 5.6+)
$args = ['Modern', 'PHP'];
greet(...$args); // Hello, Modern PHP
<?php
class Math {
public static function add($a, $b) { return $a + $b; }
public static function sum(...$nums) { return array_sum($nums); }
}
// 靜態方法呼叫
call_user_func(['Math', 'add'], 1, 2); // 3
call_user_func_array(['Math', 'sum'], [1,2,3,4]); // 10
// 現代寫法
echo Math::add(1, 2); // 直接呼叫更簡潔
<?php
class Greeter {
private $prefix;
public function __construct($prefix) { $this->prefix = $prefix; }
public function greet($name) { return $this->prefix . ' ' . $name; }
}
$greeter = new Greeter('Hi');
call_user_func([$greeter, 'greet'], 'Alice'); // Hi Alice
call_user_func_array([$greeter, 'greet'], ['Bob']); // Hi Bob
這兩個函數僅能在**函數內部**使用,用於處理不定參數。
<?php
function process(...$args) {
$count = func_num_args(); // 或 count($args)
match ($count) {
1 => handleSingle($args[0]),
2 => handlePair($args[0], $args[1]),
default => handleMultiple($args),
};
}
function handleSingle($a) { echo "Single: $a\n"; }
function handlePair($a, $b) { echo "Pair: $a, $b\n"; }
function handleMultiple(array $args) { echo "Multiple: " . implode(', ', $args) . "\n"; }
process('A');
process('A', 'B');
process('A', 'B', 'C', 'D');
<?php
function logger(callable $fn): callable {
return function(...$args) use ($fn) {
$start = microtime(true);
$result = $fn(...$args);
$time = microtime(true) - $start;
error_log(sprintf('[LOG] %s(%s) took %.4fs',
$fn instanceof Closure ? 'closure' : (is_array($fn) ? $fn[1] : $fn),
json_encode($args),
$time
));
return $result;
};
}
$loggedAdd = logger(fn($a, $b) => $a + $b);
echo $loggedAdd(10, 20); // 30,並記錄日誌
<?php
function modify(&$value) {
$value *= 2;
}
$num = 5;
call_user_func('modify', $num); // 錯誤:需傳參考
call_user_func('modify', &$num); // 正確(PHP 5.3+ 廢棄呼叫時傳參考)
call_user_func_array('modify', [&$num]); // 正確
// 正確現代寫法:定義函數參數為參考
function modifyRef(&$value) { $value *= 2; }
modifyRef($num); // 直接呼叫最清晰
<?php
class Router {
private array $routes = [];
public function add(string $method, string $pattern, callable $handler): void {
$this->routes[] = compact('method', 'pattern', 'handler');
}
public function dispatch(string $method, string $uri): mixed {
foreach ($this->routes as $route) {
if (strtoupper($route['method']) !== strtoupper($method)) continue;
$pattern = preg_replace('/\{(\w+)\}/', '(?P<$1>[^/]+)', $route['pattern']);
if (preg_match("#^$pattern$#", $uri, $matches)) {
// 過濾數字鍵,保留命名捕獲組
$params = array_filter($matches, 'is_string', ARRAY_FILTER_USE_KEY);
return call_user_func_array($route['handler'], $params);
}
}
throw new Exception('404 Not Found');
}
}
$router = new Router();
$router->add('GET', '/user/{id}', fn($id) => "User $id");
$router->add('POST', '/user', fn($name) => "Created $name");
echo $router->dispatch('GET', '/user/42'); // User 42