How to call PHP anonymous function with different order of arguments

前端 未结 1 621
失恋的感觉
失恋的感觉 2021-01-03 16:10

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() functi

相关标签:
1条回答
  • 2021-01-03 17:00

    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);
    
    0 讨论(0)
提交回复
热议问题