Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

getting function's argument names

Tags:

php

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?

like image 768
Gotys Avatar asked Apr 22 '10 16:04

Gotys


People also ask

How get arguments name in Python?

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.

What are the arguments of a function called?

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.

What are the three types of function arguments?

5 Types of Arguments in Python Function Definition:keyword arguments. positional arguments. arbitrary positional arguments.

Do parameter names and argument names have to be the same?

The caller's arguments passed to the function's parameters do not have to have the same names.


2 Answers

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 ) 
like image 113
Tom Haigh Avatar answered Oct 25 '22 17:10

Tom Haigh


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" } 
like image 24
Lucas Bustamante Avatar answered Oct 25 '22 17:10

Lucas Bustamante