草庐IT

php - 闭包重载 : is it possible to inspect the number of arguments a PHP closure has without executing it?

coder 2024-01-04 原文

我想做什么

我想检查一个闭包(作为变量传递)以确定它需要多少个参数。本质上,我想重载传统意义上的闭包,只是以不同的方式对待它。

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

如果可以更好地解释,请告诉我以便对其进行编辑。

背景资料

根据闭包的参数数量,我会调整它的调用方式。我需要这样做以通过循环节省昂贵的迭代。

请注意

  • 我正在使用 PHP5.3
  • 提醒一下,我不想执行函数,因此不能使用 func_num_args

最佳答案

Reflection :

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

关于php - 闭包重载 : is it possible to inspect the number of arguments a PHP closure has without executing it?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9606865/

有关php - 闭包重载 : is it possible to inspect the number of arguments a PHP closure has without executing it?的更多相关文章

随机推荐