如何使用不同的参数顺序调用PHP匿名函数 [英] How to call PHP anonymous function with different order of arguments

查看:192
本文介绍了如何使用不同的参数顺序调用PHP匿名函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想调用一个匿名函数(lambda或闭包),它有一些参数,我知道参数名,但我不知道他们的顺序! call_user_func_array()函数可以使用参数数组调用函数,但是数组不能是关联数组来设置所需参数的每个值,以下代码是我尝试解决我的问题,但是它们不起作用!

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!

功能:

$function = function ($b, $c, $a) {
    echo "a=" . $a . " & b=" . $b . " & c=" . $c;
};

我所需的输出:

a=1 & b=2 & c=3

我的尝试次数:

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

产量输出:

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

这篇关于如何使用不同的参数顺序调用PHP匿名函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆