Sometimes you only know which function to call while the program is running. PHP supports that.
Variable functions
If a variable holds a function name as a string, you can call it with brackets.
<?php
$function = "strtoupper";
echo $function("php");
PHP
call_user_func()
call_user_func() calls any callable. call_user_func_array() takes the arguments as an array.
<?php
function add(int $a, int $b): int
{
return $a + $b;
}
echo call_user_func("add", 2, 3) . "\n";
echo call_user_func_array("add", [10, 20]);
5
30
Today you can usually write $callable(...$args), which does the same thing.
Check first
<?php
function hello(): string
{
return "hi";
}
var_dump(function_exists("hello"));
var_dump(function_exists("nothing"));
var_dump(is_callable("hello"));
bool(true)
bool(false)
bool(true)
A safe dispatch table
Never call a function name that comes from the user ($_GET["action"]). An attacker could run any function. Instead, keep a list of allowed actions.
<?php
$actions = [
"greet" => fn(string $name) => "Hello, $name",
"shout" => fn(string $name) => strtoupper($name) . "!",
];
$requested = "shout"; // imagine this came from the URL
if (isset($actions[$requested])) {
echo $actions[$requested]("Asha");
} else {
echo "Unknown action";
}
ASHA!
Only the keys in $actions can run. Anything else is rejected.
Never run user input as a function name
$_GET["fn"]() hands control of your server to the visitor. Use an allow-list array as shown above.Why this matters in WordPress
call_user_func_array(). When you pass a function to add_action(), that is what happens behind the scenes.