I'm using PHP and the call_user_func_array function to make dynamic calls. I create an array of function names with their corresponding arguments which then get executed in a loop. e.g.:
$methods = [
[ 'myfunction1', [$arg1, $arg2] ],
[ 'myfunction2', [$arg3, $arg4] ],
];
foreach ($methods as $method) {
call_user_func_array($method[0],$method[1]);
}
Whilst this works fine, the problem I'm facing is that at the moment I define the $methods array, some of the arguments have not been defined yet (e.g. $arg1,$arg4 have, $arg2 and $arg3 haven't) BUT they are defined by the time the function is called.
Therefore I'm looking for a way to tell the function where to find the value for that argument. So far what I've come up with is to replace the variable with a string representing the name of the variable:
$methods = [
[ 'myfunction1', [$arg1, 'ARG2'] ],
[ 'myfunction2', ['ARG3', $arg4] ],
];
Then in the foreach loop, I go through each argument, check if it is a string and it that string matches a variable I replace the string with the value of that variable:
foreach ($methods as $method) {
foreach ($method[1] as $k => $arg) {
if (is_string($arg)) {
$name = strtolower($arg);
if (isset(${$name})) {
$method[1][$k] = ${$name};
}
}
}
call_user_func_array($method[0], $method[1]);
}
While this works, I'm wondering whether there are other known approaches used in PHP, as it might help me improve my code.
Do you know of any other way I could define dynamical calls with some of the arguments not being set at the time of definition?
You could use an anonymous function as the unknown argument that returns the value of the argument when called. This is working code:
function myfunction($arg1, $arg2)
{
echo "\nARGS: $arg1, $arg2";
}
$arg2func = function() {
return 'foo';
};
$arg3func = function() {
return 'bar';
};
$arg1 = 'baz';
$arg4 = 'chopchop';
$methods = [
[ 'myfunction', [$arg1, $arg2func] ],
[ 'myfunction', [$arg3func, $arg4] ],
];
foreach ($methods as $method) {
foreach ($method[1] as $k => $arg) {
if (is_callable($arg)) {
$method[1][$k] = $arg();
}
}
call_user_func_array($method[0], $method[1]);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With