3

I'm calling a function with 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.

Thanks!

2 Answers 2

8

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

1
  • yes but the callback in the question is array($this, 'myFunction') , which implies the code is calling a method on itself
    – Tom Haigh
    Jan 31, 2009 at 12:19
1

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.

See manual entry for func_get_args() to see an illustration about this.

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:

Warning: Wrong parameter count for strpos() in Command line code on line [...]
2
  • Ok, but if it fails I need to call another function. I'll edit my post. Thanks!
    – Vallières
    Jan 30, 2009 at 23:36
  • It will fail for many built-in functions. Only userspace functions are the ones that php is forgiving of wrt superfluous args. Jan 30, 2009 at 23:52

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.