drrqwokuz71031449 2013-11-16 18:53
浏览 16

在没有代码生成的情况下定义匿名函数的arity

It is possible to determine how many arguments a function accepts by using reflection.

I want to be able to define a function compose that performs function composition. That is to say, compose($f, $g) should produce a new function that returns $f($g($x)).

I have a sample implementation here:

function compose()
{
    $fns = func_get_args();
    $prev = array_shift($fns);

    foreach ($fns as $fn) {
        $prev = function ($x) use ($fn, $prev) {
            $args = func_get_args();
            return $prev(call_user_func_array($fn, $args));
        };
    }

    return $prev;
}

When composing $f and $g, $g may have an arity higher than 1. Which means it can take more than one argument. Thus, the function returned by compose($f, $g) may also take more than one argument -- it takes exactly the same arguments as $g.

The problem with this implementation is that there is no way to control the exposed arity of what compose returns. In this case it is always 1, because of the function ($x) .... When trying to determine the arity using reflection, it will always return 1 instead of that of $g.

Is there a way to change the amount of arguments of an anonymous function seen by PHP's reflection system, without using eval and other code generation techniques?

  • 写回答

4条回答 默认 最新

  • douliexing2195 2013-11-16 19:46
    关注

    The moment you introduce func_get_args() into a function should invalidate any hope of being able to determine its true arity. At that point, the arity is really only defined by the function's logic, and cannot be determined by reflection or static code analysis.

    I've written a compose-like implementation before, but it just assumed that the functions you are composing both have an arity of 1.

    评论

报告相同问题?