tags:

views:

43

answers:

1

in PHP Consider this function:

function test($name, $age) {}

I need to somehow extract the parameter names (for generating custom documentations automatically) so that I could do something like:

get_func_argNames('test');

and it would return Array['name','age'] .

Is this even possible in PHP ?

+9  A: 

You can use Reflection :

function get_func_argNames($funcName) {
    $f = new ReflectionFunction($funcName);
    $result = array();
    foreach ($f->getParameters() as $param) {
        $result[] = $param->name;   
    }
    return $result;
}

print_r(get_func_argNames('get_func_argNames'));


//output
Array
(
    [0] => funcName
)
Tom Haigh
Thank you very much . And if I want to use this to get Class Method's arguments?
Gotys
@Gotys http://de3.php.net/manual/en/class.reflectionmethod.php
Gordon
You can use ReflectionMethod, e.g. `new ReflectionMethod('classname', 'methodname');` The rest should be the same.
Tom Haigh
Gordon, you beat me to it. Thanks
Tom Haigh
Excellent! Thank you all!
Gotys
Ok, sorry for being "slow", but is there any way to get the default value of a parameter?public function test($age = 30)Get I get "30" along with "age" ?
Gotys
@Gotys: look up ReflectionParameter, you get an array of these back from ReflectionFunction::getParameters(). In the above example I only use the name property, but there is a defaultValue() method which should help you
Tom Haigh