How to get function's parameters names in PHP?

帅比萌擦擦* 提交于 2020-02-19 09:41:06

问题


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't want to repeat myself when using setting variables passed as arguments through a method:

public function myFunction($paramJohn, $paramJoe, MyObject $paramMyObject)
{
     $this->paramJohn = $paramJohn;
     $this->paramJoe = $paramJoe;
     $this->paramMyObject = $paramMyObject;
}

Ideally I could do something like:

foreach (func_get_params() as $param)
   $this->${$param} = ${$param};
}

Is this an overkill, is it a plain stupid idea, or is there a much better way to make this happen?


回答1:


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) {
  }
}



回答2:


While it's not impossible to do it, it's usually better to use another method. Here is a link to a similar question on SO :

How to get a variable name as a string in PHP?

What you could do is pass all your parameters inside of an object, instead of passing them one by one. I'm assuming you are doing this in relation to databases, you might want to read about ORMs.




回答3:


Code snippet that creates an array containing parameter names as keys and parameter values as corresponding values:

$ref = new ReflectionFunction(__FUNCTION__);

$functionParameters = [];
foreach($ref->getParameters() as $key => $currentParameter) {
    $functionParameters[$currentParameter->getName()] = func_get_arg($key);
}


来源:https://stackoverflow.com/questions/17455043/how-to-get-functions-parameters-names-in-php

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!