Home >Backend Development >PHP Tutorial >How Can I Dynamically Call Functions in PHP Using Variable Names?
Dynamically Calling Functions with Variable Names
In PHP, it is possible to invoke a function by its name stored in a variable. This technique is useful in scenarios where the function to be executed is unknown at compile time or needs to be dynamically determined based on input or configuration.
Two Options for Dynamic Function Invocation
To execute a function based on a variable name, there are two common approaches:
<?php function foo() { // Function code } function bar() { // Function code } $functionName = "foo"; $functionName(); // Calls the foo function // Providing parameters in an array $parameters = ['Hello', 'World']; call_user_func_array('printf', $parameters); // Outputs "HelloWorld" ?>
Advanced Usage with Array Unpacking and Dynamic Object Creation
If you need to pass an array of arguments to a function, you can use the array unpacking operator:
$function_name = 'trim'; $parameters = ['aaabbb', 'b']; echo $function_name(...$parameters); // Outputs "aaa"
Furthermore, you can create an object and call its method dynamically:
$class = 'DateTime'; $method = 'format'; echo (new $class)->$method('d-m-Y'); // Outputs the current date in "d-m-Y" format
Alternatively, you can call a static method of a class:
$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 in PHP Using Variable Names?. For more information, please follow other related articles on the PHP Chinese website!