如何在 PHP 中获取函数的参数名称? [英] How to get function's parameters names in PHP?

查看:278
本文介绍了如何在 PHP 中获取函数的参数名称?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在寻找一种反向的 func_get_args().我想知道在定义函数时参数是如何命名的.这样做的原因是我不想在使用通过方法作为参数传递的设置变量时重复自己:

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?

推荐答案

你可以使用 Reflection:

You could use Reflection:

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

由于您在类中使用它,因此您可以使用 ReflectionMethod 代替ReflectionFunction:

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

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

这是一个工作示例:

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);

上面var_dump() 打印的地方:

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

这篇关于如何在 PHP 中获取函数的参数名称?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆