如何动态检查 PHP 中匿名函数的预期参数数量? [英] How can I dynamically check the number of arguments expected of an anonymous function in PHP?

查看:25
本文介绍了如何动态检查 PHP 中匿名函数的预期参数数量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以在 PHP 中获取匿名函数预期的参数数量?我知道 ReflectionMethod,但这似乎只有在该方法是在类上定义时才有效.就我而言,匿名函数要么有 1 个参数,要么有两个参数.我更愿意正确地进行检查,而不是将第一个调用包装在 try/catch 中,如果第一个调用失败,则使用 2 个参数重试.

Is it possible to get the number of arguments expected of an anonymous function in PHP? I'm aware of ReflectionMethod, but that seems to only work if the method is defined on a class. In my case, the anonymous function is either going to have 1 or two arguments. I'd prefer to do the checking correctly, rather than wrapping the first call in a try/catch, and trying again with 2 parameters if the first has failed.

推荐答案

试试这个:

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

A few months ago I wrote this up in a bit more detail here: http://onehackoranother.com/logfile/2009/05/finding-the-arity-of-a-closure-in-php-53

这篇关于如何动态检查 PHP 中匿名函数的预期参数数量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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