How to call PHP anonymous function with different

2020-03-01 03:57发布

问题:

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

回答1:

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);