[英]Closure overloading: is it possible to inspect the number of arguments a PHP closure has without executing it?
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. 如果可以更好地解释这一点,请告诉我,以便进行编辑。
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.
我需要这样做以通过循环节省昂贵的迭代。
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.