Home >Backend Development >PHP Tutorial >How Can I Dynamically Call Functions and Methods in Programming?
In programming, it's often useful to be able to call a function based on its name stored in a variable. This technique allows for greater flexibility and code reuse.
To call a function from a variable, you can use one of the following methods:
1. Direct Function Call:
Assign the function name to a variable using single or double quotes (e.g., $functionName = "foo") and then call the function directly using the variable (e.g., $functionName()).
2. call_user_func():
The call_user_func() function takes a function name stored in a variable as its first argument and any necessary parameters as subsequent arguments.
Example:
function foo() { // Code } function bar() { // Code } $functionName = "foo"; // Call the function using direct function call $functionName(); // Call the function using call_user_func() call_user_func($functionName);
To pass parameters stored in a variable array, use the array unpacking operator (...):
$function_name = 'trim'; $parameters = ['aaabbb', 'b']; echo $function_name(...$parameters); // aaa
To dynamically create an object and call its method, use the following syntax:
$class = 'DateTime'; $method = 'format'; echo (new $class)->$method('d-m-Y');
For static methods:
$class = 'DateTime'; $static = 'createFromFormat'; $date = $class::$static('d-m-Y', '17-08-2023');
The above is the detailed content of How Can I Dynamically Call Functions and Methods in Programming?. For more information, please follow other related articles on the PHP Chinese website!