Senica Gonzalez
Senica Gonzalez

Reputation: 8182

Get number of parameters a function requires

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?

Upvotes: 11

Views: 7444

Answers (2)

James Williams
James Williams

Reputation: 4216

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

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

$method = new ReflectionMethod('foo', 'bar');
$num = $method->getNumberOfParameters();

Upvotes: 1

KingCrunch
KingCrunch

Reputation: 131871

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

Upvotes: 20

Related Questions