Friday, March 4, 2011

how to dynamically check number of arguments of a function in php

how can I check at runtime home many parameters a method or a function have in PHP.

example

class foo {
   function bar ( arg1, arg2 ){
    .....
   }
}

I will need to know if there is a way to run something like

get_func_arg_number ( "foo", "bar" )

and the result to be

2
From stackoverflow
  • You're looking for the reflection capabilities in PHP5 -- documentation here.

    Specifically, look at the ReflectionFunction and ReflcetionMethod classes.

  • I believe you are looking for func_num_args()

    http://us3.php.net/manual/en/function.func-num-args.php

    gnud : No. This is for use inside functions, and says how many arguments were passed to the function you are in.
    JW : That will return the number of arguments passed to the function when you've called it. The OP is looking for the number of arguments in the function signature, which may be different.
  • You need to use reflection to do that.

    $method = new ReflectionMethod('foo', 'bar');
    $num = $method->getNumberOfParameters();
    
  • Reflection is what you're after here

    class foo {
       function bar ( $arg1, $arg2 ){
    
       }
    }
    $ReflectionFoo = new ReflectionClass('foo');
    echo $ReflectionFoo->getMethod('bar')->getNumberOfParameters();
    

0 comments:

Post a Comment