getting function's argument names
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 开发者_如何学JAVAit would return:
Array['name','age']
Is this even possible in PHP?
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
)
It's 2019 and no one said this?
Just use get_defined_vars()
:
class Foo {
public function bar($a, $b) {
var_dump(get_defined_vars());
}
}
(new Foo)->bar('first', 'second');
Result:
array(2) {
["a"]=>
string(5) "first"
["b"]=>
string(6) "second"
}
This is an old question I happened on looking for something other then Reflection, but I will toss out my current implementation so that it might help someone else. Using array_map
For a method
$ReflectionMethod = new \ReflectionMethod($class, $method);
$params = $ReflectionMethod->getParameters();
$paramNames = array_map(function( $item ){
return $item->getName();
}, $params);
For a function
$ReflectionFunction = new \ReflectionFunction('preg_replace');
$params = $ReflectionFunction->getParameters();
$paramNames = array_map(function( $item ){
return $item->getName();
}, $params);
echo '<pre>';
var_export( $paramNames );
Outputs
array(
'0' => 'regex',
'1' => 'replace',
'2' => 'subject',
'3' => 'limit',
'4' => 'count'
)
Cheers,
In addition to Tom Haigh's answer if you need to get the default value of optional attributes:
function function_get_names($funcName){
$attribute_names = [];
if(function_exists($funcName)){
$fx = new ReflectionFunction($funcName);
foreach ($fx->getParameters() as $param){
$attribute_names[$param->name] = NULL;
if ($param->isOptional()){
$attribute_names[$param->name] = $param->getDefaultValue();
}
}
}
return $attribute_names;
}
Useful for variable type validation.
@Tom Haigh, or do it more classy:
function getArguments( $funcName ) {
return array_map( function( $parameter ) { return $parameter->name; },
(new ReflectionFunction($funcName))->getParameters() );
}
// var_dump( getArguments('getArguments') );
func_get_args
function my($aaa, $bbb){
var_dump( func_get_args() );
}
my("something","something"); //result: array('aaa' => 'something', 'bbb' => 'something');
also, there exists another global functions: get_defined_vars()
, that returns not only function, but all variables.
精彩评论