PHP: function argument names

I need to get the names of anonymous function arguments.

eg:.

$func = function ( $param1, $param2 ) { ... };
$names = DO_SOMETHING($func); 
// after this $names should become something like array('param1', param2')

Theoretically, this is possible because it var_dump($func)says that it $funcis an object of the class Closureand has a property parameterthat array('param1', 'param2').

The official documentation on php.net does not describe the methods of the Closure class that can help me.

I tried to access this property directly, but PHP has died from a fatal mistake: Closure object cannot have properties.

I tried to get object vars with get_object_vars, but it seems that the property is parameterdeclared as private (in any case, it get_object_varsdoes not return it).

The only way I know is to intercept the output var_dumpand analyze it, but since we easily understand that this is not how we should write our scripts =)

Sorry for my bad english.

+5
source share
1 answer

I can’t try this at the moment, but look:

http://www.php.net/manual/en/class.reflectionfunction.php

special

http://www.php.net/manual/en/reflectionfunctionabstract.getparameters.php

Maybe it will work.

Edit: Try the following:

$func = function ( $param1, $param2 ) {
    /* some code */
};

$refFunc = new ReflectionFunction($func);
foreach ($refFunc->getParameters() as $refParameter) {
    echo $refParameter->getName(), '<br />';
}
+9
source

All Articles