Member-only story

Dynamic function invocation in PHP

Beck Moulton
3 min readApr 30, 2024

--

The dynamic function call feature in PHP allows programmers to choose the function to call at runtime based on variable values or other dynamic conditions. This is very useful for scenarios where program behavior needs to be adjusted based on user input, configuration settings, or other factors. This article will delve into the main methods of implementing dynamic function calls in PHP and provide some practical tips and examples.

Variable function

PHP supports variable function, which means the function name is stored in a variable and executed by following the variable with parentheses.

Example:

function sayHello() {
echo "你好,世界!";
} $functionName = "sayHello" ;
$functionName(); // 调用函数,输出:你好,世界!

This method is simple and suitable for simple dynamic function calls. However, it does not directly support passing parameters to functions.

call_user_func () implement dynamic function call

call_user_func ()Function provides a more flexible way of calling dynamic functions, supporting passing parameters. It takes the function name as the first parameter, followed by any parameters to be passed to the function.

Grammar:

call_user_func($callback, ...$args): mixed

Example without parameters:

function sayHello() {
echo…

--

--

Beck Moulton
Beck Moulton

Written by Beck Moulton

Focus on the back-end field, do actual combat technology sharing Buy me a Coffee if You Appreciate My Hard Work https://www.buymeacoffee.com/BeckMoulton

No responses yet