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: