How to get function's parameters names in PHP?

前端 未结 3 1885
情话喂你
情话喂你 2021-02-07 18:28

I\'m looking for a sort of reversed func_get_args(). I would like to find out how the parameters were named when function was defined. The reason for this is I don\

3条回答
  •  猫巷女王i
    2021-02-07 19:08

    You could use Reflection:

    $ref = new ReflectionFunction('myFunction');
    foreach( $ref->getParameters() as $param) {
        echo $param->name;
    }
    

    Since you're using this in a class, you can use ReflectionMethod instead of ReflectionFunction:

    $ref = new ReflectionMethod('ClassName', 'myFunction');
    

    Here is a working example:

    class ClassName {
        public function myFunction($paramJohn, $paramJoe, $paramMyObject)
        {
            $ref = new ReflectionMethod($this, 'myFunction');
            foreach( $ref->getParameters() as $param) {
                $name = $param->name;
                $this->$name = $$name;
            }
        }
    }
    
    $o = new ClassName;
    $o->myFunction('John', 'Joe', new stdClass);
    var_dump( $o);
    

    Where the above var_dump() prints:

    object(ClassName)#1 (3) {
      ["paramJohn"]=>
      string(4) "John"
      ["paramJoe"]=>
      string(3) "Joe"
      ["paramMyObject"]=>
      object(stdClass)#2 (0) {
      }
    }
    

提交回复
热议问题