Dynamic Function Invocation from Variable
In PHP, invoking a function dynamically based on a value stored in a variable is an essential technique for creating versatile and modular applications.
To execute a function whose name is held in a string, you can use the following methods:
Dynamic Function Invocation with Parameters
If you need to pass parameters to the dynamic function, you can use the array unpacking operator:
$function_name = 'trim'; $parameters = ['aaabbb', 'b']; echo $function_name(...$parameters); // aaa
Dynamic Object and Method Invocation
Dynamically creating an object and invoking its method:
$class = 'DateTime'; $method = 'format'; echo (new $class)->$method('d-m-Y');
Dynamic Static Method Invocation
To call a static method dynamically:
$class = 'DateTime'; $static = 'createFromFormat'; $date = $class::$static('d-m-Y', '17-08-2023');
These techniques empower you to achieve greater flexibility and code reusability in your PHP applications.
The above is the detailed content of How Can I Dynamically Invoke Functions and Methods in PHP?. For more information, please follow other related articles on the PHP Chinese website!