PHP: Get argument count

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?

Upvotes: 3

Views: 2400

Answers (1)

Jacob Relkin
Jacob Relkin

Reputation: 163238

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.

Upvotes: 9

Related Questions