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?
To extract the number and names of the arguments from a function or function[something] to return ("arg1", "arg2"), we use the inspect module. The given code is written as follows using inspect module to find the parameters inside the functions aMethod and foo.
Argument and Parameter Names When a function's arguments are variables, the argument names (in the function call) and the parameter names (in the function definition) may be the same or they may be different.
5 Types of Arguments in Python Function Definition:keyword arguments. positional arguments. arbitrary positional arguments.
The caller's arguments passed to the function's parameters do not have to have the same names.
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" }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With