3

This was incredibly surprising to see that PHP has no obvious function to do what I'm looking for, so I'll ask here.

How would you go about getting the number of arguments a particular function has outside of the function (just like func_num_args only from outside the function).

The solution can't actually execute the function (that would be defeating the purpose), and I'd like to do it (preferably) without any sort of reflection class.

Possible?

1 Answer 1

9

Oh, you can use the ReflectionFunction class, which inherits from ReflectionFunctionAbstract, which defines the getNumberOfParameters function:

$func_reflection = new ReflectionFunction('function_name');
$num_of_params = $func_reflection->getNumberOfParameters();

Note: This will only work on user functions, not class or instance functions.

Sign up to request clarification or add additional context in comments.

7 Comments

So now my concern is cost: is using the reflection class expensive?
@Di-0xide, I think it is, but what choice do you have?
@Jacob Relkin, true... I may do a manual alternative for my solution instead of trying to do it dynamically. For the sake of the question your answer is a valid solution. Thanks for the help!
You can do it on class methods just as easily - php.net/manual/en/reflectionclass.getmethod.php
@CaseySoftware True, my point is that ReflectionFunction only works on user functions.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.