Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 526
Senica Gonzalez Avatar asked Oct 14 '11 23:10

Senica Gonzalez


People also ask

How do you find the number of parameters passed to a function?

If you want to check whether a particular parameter was passed to a procedure, you can use the %PARMNUM built-in function to obtain the number of the parameter.

How many parameters can of function requires?

The main function can be defined with no parameters or with two parameters (for passing command-line arguments to a program when it begins executing). The two parameters are referred to here as argc and argv, though any names can be used because they are local to the function in which they are declared.

How many parameters a function should have?

The ideal number of arguments for a function is zero (niladic). Next comes one (monadic), followed closely by two (dyadic). Three arguments (triadic) should be avoided where possible. More than three (polyadic) requires very special justification - and then shouldn't be used anyway.

How many parameters can a Python function have?

Of those, the most significant byte represent the number of keyword arguments on the stack and the least significant byte the number of positional arguments on the stack. Therefore, you can have at most 0xFF == 255 keyword arguments or 0xFF == 255 positional arguments.


2 Answers

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

like image 149
KingCrunch Avatar answered Sep 21 '22 01:09

KingCrunch


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();
like image 40
James Williams Avatar answered Sep 19 '22 01:09

James Williams