46

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?

1stthomas
  • 731
  • 2
  • 15
  • 22
Gotys
  • 1,371
  • 2
  • 13
  • 22

6 Answers6

78

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
  • 57,217
  • 21
  • 114
  • 142
  • Thank you very much . And if I want to use this to get Class Method's arguments? – Gotys Apr 22 '10 at 16:20
  • 11
    You can use ReflectionMethod, e.g. `new ReflectionMethod('classname', 'methodname');` The rest should be the same. – Tom Haigh Apr 22 '10 at 16:23
  • 1
    Gordon, you beat me to it. Thanks – Tom Haigh Apr 22 '10 at 16:24
  • 1
    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 Apr 22 '10 at 16:40
  • 2
    @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 Apr 22 '10 at 21:17
  • Thank you for that. Works rather well and me personally, I don't care if it's not the prettiest solution in the world. :-) – dimitarvp Aug 30 '12 at 14:58
32

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"
}
Lucas Bustamante
  • 15,821
  • 7
  • 92
  • 86
  • 2
    "This function returns a multidimensional array containing a list of all defined variables, be them environment, server or user-defined variables, within the scope that get_defined_vars() is called. " It appears to return everything available, including globals and whatnot. So be cautious about using this one. – ADJenks Oct 21 '22 at 00:12
  • 1
    @ADJenks, it doesn't include globals if called inside of a function. – 1234ru Mar 09 '23 at 18:44
8

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,

ArtisticPhoenix
  • 21,464
  • 2
  • 24
  • 38
4

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.

RafaSashi
  • 16,483
  • 8
  • 84
  • 94
3

@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') );
David Refoua
  • 3,476
  • 3
  • 31
  • 55
-1

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.

T.Todua
  • 53,146
  • 19
  • 236
  • 237
  • 2
    I think the reason it's not is because the 'result' comment is wrong. `get_defined_vars()` would output: `array('aaa' => 'something', 'bbb' => 'something');`. Also, be aware, that function will give you *all* variables defined prior to its call, not just function parameters. – kmuenkel Jun 21 '17 at 18:35
  • 1
    @T.Todua You're welcome. But you kind of had it right the first time. `get_defined_vars()` was the correct answer, so long you're aware of when to use it. It was just the comment about what the output would look like that was wrong. But it looks like you also changed your answer to reflect `func_get_args()` instead. I don't believe that would give variable-named keys like you indicate there, just numeric indices. Unlike `get_defined_vars()`, `func_get_args()` would also end up omitting any parameters that are set by a default value rather than an argument. – kmuenkel Jul 07 '17 at 14:25
  • 3
    With this code I do not have the same result. I have `array(0 => 'something', 1 => 'something');`. What php version do you use? – FreeLightman Jun 09 '18 at 07:29
  • 1
    `func_get_args()` does not return the parameter name as the array key, but its order as an int. – Lucas Bustamante Aug 23 '19 at 16:06