Calling Functions Dynamically Using Variable Strings
In programming, particularly in PHP, you may encounter situations where you need to call a function whose name is stored in a variable. This can be useful for flexibility and code reusability.
Let's consider the example you provided:
function foo() { // code here } function bar() { // code here } $functionName = "foo";
To call the function stored in $functionName, you can use:
Additional Considerations:
$parameters = ['aaabbb', 'b']; $function_name = 'trim'; echo $function_name(...$parameters); // aaa
$class = 'DateTime'; $method = 'format'; echo (new $class)->$method('d-m-Y');
$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 Strings?. For more information, please follow other related articles on the PHP Chinese website!