tags:

views:

31

answers:

3

Hi,

Is there a way to detect the number of arguments a function in a class has?

What I want to do is the following.

$class = 'foo';
$path = 'path/to/file';
if ( ! file_exists($path)) {
  die();
}

require($path);

if ( ! class_exists($class)) {
  die();
}

$c = new class;

if (num_function_args($class, $function) == count($url_segments)) {
  $c->$function($one, $two, $three);
}

Is this possible?

+1  A: 

Using reflection, but this is really an overhead in your code; and a method can have any number of arguments without their explicitly being defined in the method definition.

$classMethod = new ReflectionMethod($class,$method);
$argumentCount = count($classMethod->getParameters());
Mark Baker
I don't think I will use it but thanks for the answer.
JasonS
+1  A: 

Use call_user_func_array instead, if you pass too many parameters, they will simply be ignored.

Demo

class Foo {
   public function bar($arg1, $arg2) {
       echo $arg1 . ', ' . $arg2;
   }
}


$foo = new Foo();

call_user_func_array(array($foo, 'bar'), array(1, 2, 3, 4, 5));

Will output

1, 2

For dynamic arguments, use func_get_args like this :

class Foo {
   public function bar() {
       $args = func_get_args();
       echo implode(', ', $args);
   }
}


$foo = new Foo();

call_user_func_array(array($foo, 'bar'), array(1, 2, 3, 4, 5));

Will output

1, 2, 3, 4, 5
Yanick Rochon
A: 

To get the number of arguments in a Function or Method signature, you can use

Example

$rf = new ReflectionMethod('DateTime', 'diff');
echo $rf->getNumberOfParameters();         // 2
echo $rf->getNumberOfRequiredParameters(); // 1

To get the number of arguments passed to a function at runtime, you can use

  • func_num_args — Returns the number of arguments passed to the function

Example

function fn() {
    return func_num_args();
}
echo fn(1,2,3,4,5,6,7); // 7
Gordon