Gerald Gerald - 2 months ago 19
PHP Question

Parameter List of Anonymous Function / Closure

Let's assume I have an anonymous function:

$my_function = function($par1, $par2) {
// Do something
};


Is there a way to get a parameter list without executing the function in any way? Something like this:

$parameter_list = get_func_params($my_function);


The result should contain a list of all required function parameters:

Array (
[0] => par1
[1] => par2
)


What code could
get_func_params
contain to return such an Array?



The background is that I use generic code that should check if the provided closure implements the required parameter logic.

I don't want to solve this problem using Classes or Interfaces.

Answer

Please try this:

$my_function = function($par1, $par2) {
    // Do something
};

$reflection = new ReflectionFunction($my_function);
var_dump($reflection->getParameters());
Comments