简体   繁体   English

关闭重载:是否可以检查PHP闭包的参数数量而不执行它?

[英]Closure overloading: is it possible to inspect the number of arguments a PHP closure has without executing it?

What I want to do 我想做的事

I want to inspect a closure (passed as a variable) to determine how many arguments it expects. 我想检查一个闭包(作为变量传递)以确定它期望的参数数量。 Essentially, I want to overload a closure in the traditional sense, only by treating it differently. 从本质上讲,我想在传统意义上重载一个闭包,只是以不同的方式处理它。

function someMethod(Closure $callback) {
    $varA;
    $varB;
    $varC;
    if($callback->getNumArgs() == 3) {
        $callback($varA, $varB, $varC);
    }
    else {
        $callback($varC, $varA);
    }
}

If this could be explained better, please let me know so it can be edited. 如果可以更好地解释这一点,请告诉我,以便进行编辑。

Background information 背景资料

Depending on how many arguments the closure takes, I will adjust the way in which it's called. 根据闭包所用的参数数量,我将调整它的调用方式。 I need to do this to save expensive iterations through a loop. 我需要这样做以通过循环节省昂贵的迭代。

Please note 请注意

  • I am using PHP5.3 我使用的是PHP5.3
  • As a reminder, I do not want to execute the function and thus cannot use func_num_args 提醒一下,我不想执行该函数,因此不能使用 func_num_args

With Reflection : 有了反思

$ref = new ReflectionFunction(function($foo, $bar) {});
echo $ref->getNumberOfParameters(); // 2

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM