Skip to content

PHP Tutorial Functions

Calling Functions Dynamically

Lesson 116 of 369 2 min read By Deepak Paswan Updated Oct 5, 2026

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.

index.php
PHP
<?php
$function = "strtoupper";

echo $function("php");
Output
OUTPUT
PHP

call_user_func()

call_user_func() calls any callable. call_user_func_array() takes the arguments as an array.

index.php
PHP
<?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]);
Output
OUTPUT
5
30

Today you can usually write $callable(...$args), which does the same thing.

Check first

index.php
PHP
<?php
function hello(): string
{
    return "hi";
}

var_dump(function_exists("hello"));
var_dump(function_exists("nothing"));
var_dump(is_callable("hello"));
Output
OUTPUT
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.

index.php
PHP
<?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";
}
Output
OUTPUT
ASHA!

Only the keys in $actions can run. Anything else is rejected.

dangerous
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.
info
Why this matters in WordPress
WordPress stores callbacks by name and calls them later with call_user_func_array(). When you pass a function to add_action(), that is what happens behind the scenes.