Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get number of arguments for a class function

Tags:

function

php

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?

like image 367
JasonS Avatar asked Oct 21 '10 15:10

JasonS


3 Answers

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

  • ReflectionFunctionAbstract::getNumberOfParameters - Gets number of parameters

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
like image 118
Gordon Avatar answered Nov 20 '22 14:11

Gordon


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());
like image 38
Mark Baker Avatar answered Nov 20 '22 13:11

Mark Baker


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
like image 30
Yanick Rochon Avatar answered Nov 20 '22 14:11

Yanick Rochon