I want to call an anonymous function (lambda or closure) which has some arguments, I know the argument names but I don't know their order! The call_user_func_array() function can call the function with an array of arguments but the array cannot be an associative array to set every value for desired argument, following codes are my attempts to solve my problem but they just don't work!
The function:
$function = function ($b, $c, $a) {
echo "a=" . $a . " & b=" . $b . " & c=" . $c;
};
My desired output:
a=1 & b=2 & c=3
My attempts:
// Attempt 1
call_user_func_array($function, array("a" => 1, "b" => 2, "c" => 3));
// Attempt 2
$ref = new ReflectionFunction($function);
$ref->invokeArgs(array("a" => 1, "b" => 2, "c" => 3));
The yield output:
a=3 & b=1 & c=2
You have to pass the parameters positionally, names aren't considered at all. You can map the parameters by name to their position using reflection:
$params = array("a" => 1, "b" => 2, "c" => 3);
$ref = new ReflectionFunction($function);
$arguments = array_map(
function (ReflectionParameter $param) use ($params) {
if (isset($params[$param->getName()])) {
return $params[$param->getName()];
}
if ($param->isOptional()) {
return $param->getDefaultValue();
}
throw new InvalidArgumentException('Missing parameter ' . $param->getName());
},
$ref->getParameters()
);
$ref->invokeArgs($arguments);
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