PHP 支援變數函數:將函數名稱字串存入變數,透過變數加括號 $func() 呼叫。適用於回呼、策略模式、動態分派。
function addition($a, $b) {
echo ($a + $b) . "\n";
}
$func = "addition";
$func(3, 6); // 等同 addition(3, 6) → 輸出 9
class Math {
public static function add($a, $b) { return $a + $b; }
public function mul($a, $b) { return $a * $b; }
}
$staticCall = ['Math', 'add'];
$objCall = [new Math(), 'mul'];
echo $staticCall(2, 3) . "\n"; // 5
echo $objCall(2, 3) . "\n"; // 6
$funcs = ['strlen', 'strtoupper', 'md5'];
$str = "hello";
foreach ($funcs as $f) {
echo "$f: " . $f($str) . "\n";
}
echo()、print()、unset()、isset()、empty()、include()、require()call_user_func()、call_user_func_array() 統一呼叫if (in_array($input, $allowed)) $input();變數函數是 PHP 動態特性核心,善用白名單確保安全。