【问题标题】:How can I dynamically check the number of arguments expected of an anonymous function in PHP?如何动态检查 PHP 中匿名函数的预期参数数量?
【发布时间】:2011-01-11 12:56:24
【问题描述】:

是否可以在 PHP 中获取匿名函数的预期参数数量?我知道 ReflectionMethod,但这似乎只有在该方法是在类上定义的情况下才有效。在我的例子中,匿名函数要么有 1 个参数,要么有 2 个参数。我宁愿正确地进行检查,而不是将第一个调用包装在 try/catch 中,如果第一个调用失败,则使用 2 个参数再次尝试。

【问题讨论】:

    标签: php reflection arguments anonymous-function


    【解决方案1】:

    试试这个:

    // returns the arity of the given closure
    function arity($lambda) {
        $r = new ReflectionObject($lambda);
        $m = $r->getMethod('__invoke');
        return $m->getNumberOfParameters();
    }
    

    几个月前,我在这里更详细地写了这篇文章:http://onehackoranother.com/logfile/2009/05/finding-the-arity-of-a-closure-in-php-53

    【讨论】:

    • 请注意,根据 PHP 文档,不应依赖此方法,因为它是一个实现细节。
    • 你有参考吗?我的印象是 __invoke() 是官方的“魔术方法”:php.net/manual/en/… - 除非有一些关于闭包的特定例外
    • 太棒了,正是我需要的,谢谢!我正在查看 Reflection doco,但我缺少的是 _invoke 键。
    猜你喜欢
    • 1970-01-01
    • 2019-08-19
    • 2013-02-21
    • 1970-01-01
    • 2013-07-12
    • 1970-01-01
    • 2012-07-10
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多