PHP: Get number of parameters a function requires

2019-02-13 13:13发布

This is an extension question of PHP pass in $this to function outside class

And I believe this is what I'm looking for but it's in python not php: Programmatically determining amount of parameters a function requires - Python

Let's say I have a function like this:

function client_func($cls, $arg){ }

and when I'm ready to call this function I might do something like this in pseudo code:

if function's first parameter equals '$cls', then call client_func(instanceof class, $arg)
else call client_func($arg)

So basically, is there a way to lookahead to a function and see what parameter values are required before calling the function.

I guess this would be like debug_backtrace, but the other way around.

func_get_args() can only be called from within a function which doesn't help me here.

Any thoughts?

2条回答
等我变得足够好
2楼-- · 2019-02-13 14:15

Use Reflection, especially ReflectionFunction in your case.

$fct = new ReflectionFunction('client_func');
echo $fct->getNumberOfRequiredParameters();

As far as I can see you will find getParameters() useful too

查看更多
Viruses.
3楼-- · 2019-02-13 14:15

Only way is with reflection by going to http://us3.php.net/manual/en/book.reflection.php

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

$method = new ReflectionMethod('foo', 'bar');
$num = $method->getNumberOfParameters();
查看更多
登录 后发表回答