views:

243

answers:

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!

A: 

Who cares if it's callable or not? Wrap the call in a try block, and handle the exception if it fails.

jrockway
normal function calls don't raise exceptions, but errors.
Henrik Paul
you can convert warnings to exceptions. I don't think it's a bad suggestion actually.
troelskn
+1  A: 

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 [...]
Henrik Paul
Ok, but if it fails I need to call another function. I'll edit my post.Thanks!
valli-R
It will fail for many built-in functions. Only userspace functions are the ones that php is forgiving of wrt superfluous args.
Crescent Fresh
+4  A: 

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

Tom Haigh
ReflectionFunction might work better with just functions.
Henrik Paul
yes but the callback in the question is array($this, 'myFunction') , which implies the code is calling a method on itself
Tom Haigh
Ok thanks I'll take a look at Reflection
valli-R