Dynamic Function Calls in PHP: Variable Functions, call_user_func, and call_user_func_array
This article explains how PHP enables dynamic function invocation using variable functions, call_user_func, and call_user_func_array, provides syntax and examples, discusses practical scenarios such as event‑driven programming and plugins, and outlines safety best practices for secure implementation.
PHP provides several ways to invoke functions dynamically at runtime, allowing developers to select which function to call based on variable values, user input, or configuration.
Variable functions let a function name be stored in a variable and called by appending parentheses. Example:
function sayHello() {
echo "你好,世界!";
}
$functionName = "sayHello";
$functionName(); // outputs: 你好,世界!The call_user_func() function offers a more flexible approach, supporting argument passing. Its syntax is call_user_func($callback, ...$args) . Example without parameters:
function sayHello() {
echo "你好,世界!";
}
call_user_func('sayHello'); // outputs: 你好,世界!Example with parameters:
function greet($name) {
echo "你好,{$name}!";
}
call_user_func('greet', 'PHP'); // outputs: 你好,PHP!When an argument array is needed, call_user_func_array() accepts the function name and an array of arguments. Example:
function greet($greeting, $name) {
echo "{$greeting}, {$name}!";
}
$args = ["你好", "PHP"];
call_user_func_array('greet', $args); // outputs: 你好,PHP!Typical use cases include event‑driven programming, plugin systems, and callbacks, where functions must be selected or loaded dynamically.
Best practices advise checking function existence with function_exists() , sanitizing any user‑provided function names, preferring built‑in callbacks over eval() , and documenting dynamic call logic to maintain security and readability.
php中文网 Courses
php中文网's platform for the latest courses and technical articles, helping PHP learners advance quickly.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.