I'm calling a function with call_user_func_array :
我正在用call_user_func_array调用一个函数:
call_user_func_array(array($this, 'myFunction'), array('param1', 'param2', 'param3'));
Everything is ok unless I don't know how many parameters the function needs. If the function needs 4 parameters it sends me an error, I'd like to test if I can call the function (with an array of parameters). is_callable() doesn't allow parameters check. Edit : If the call fails I need to call another function, that's why I need a check.
除非我不知道函数需要多少参数,否则一切都还可以。如果该函数需要4个参数,它会向我发送一个错误,我想测试是否可以调用该函数(带有一个参数数组)。 is_callable()不允许参数检查。编辑:如果调用失败,我需要调用另一个函数,这就是我需要检查的原因。
Thanks!
2 个解决方案
#1
You could use reflection to get the number of parameters:
您可以使用反射来获取参数的数量:
$refl = new ReflectionMethod(get_class($this), 'myFunction');
$numParams = $refl->getNumberOfParameters();
or
$numParams = $refl->getNumberOfRequiredParameters();
See here for some more information
有关更多信息,请参见此处
#2
One way getting around this is to call the function always with a lot of arguments. PHP is designed in such a way that you can pass as many extraneous arguments as you want, and the excess ones are just ignored by the function definition.
解决这个问题的一种方法是使用大量参数调用函数。 PHP的设计方式使您可以根据需要传递尽可能多的无关参数,而多余的参数只会被函数定义忽略。
See manual entry for func_get_args()
to see an illustration about this.
请参阅func_get_args()的手动输入以查看有关此内容的说明。
Edit: As user crescentfresh pointed out, this doesn't work with built-in functions, only user defined functions. If you try to pass too many (or few) arguments into a built-in function, you'll get the following warning:
编辑:正如用户crescentfresh指出的那样,这不适用于内置函数,只适用于用户定义的函数。如果您尝试将太多(或很少)参数传递给内置函数,您将收到以下警告:
Warning: Wrong parameter count for strpos() in Command line code on line [...]
#1
You could use reflection to get the number of parameters:
您可以使用反射来获取参数的数量:
$refl = new ReflectionMethod(get_class($this), 'myFunction');
$numParams = $refl->getNumberOfParameters();
or
$numParams = $refl->getNumberOfRequiredParameters();
See here for some more information
有关更多信息,请参见此处
#2
One way getting around this is to call the function always with a lot of arguments. PHP is designed in such a way that you can pass as many extraneous arguments as you want, and the excess ones are just ignored by the function definition.
解决这个问题的一种方法是使用大量参数调用函数。 PHP的设计方式使您可以根据需要传递尽可能多的无关参数,而多余的参数只会被函数定义忽略。
See manual entry for func_get_args()
to see an illustration about this.
请参阅func_get_args()的手动输入以查看有关此内容的说明。
Edit: As user crescentfresh pointed out, this doesn't work with built-in functions, only user defined functions. If you try to pass too many (or few) arguments into a built-in function, you'll get the following warning:
编辑:正如用户crescentfresh指出的那样,这不适用于内置函数,只适用于用户定义的函数。如果您尝试将太多(或很少)参数传递给内置函数,您将收到以下警告:
Warning: Wrong parameter count for strpos() in Command line code on line [...]