php - 从php构造函数获取构造参数依赖

标签 php parameters constructor dependency-injection constructor-injection

使用 php ReflectionClass我可以找到必须在类构造函数中注入(inject)哪些参数才能创建新实例。

$class = new ReflectionClass($this->someClass);
$constructor = $class->getConstructor();
$parameters = $constructor->getParameters();

是否还有一种方法可以获取这些参数的依赖关系。 因此,如果 someClass 的构造函数如下所示:

public function __construct(Dependency $dependency){
    $this->dependency = $dependency;
}

我能以某种方式从构造函数中获取类依赖吗?

最佳答案

ReflectionMethod::getParameters返回 ReflectionParameter 的数组对象。 ReflectionParameters 有一个名为 getClass 的方法,它将返回有关参数类型提示的信息。

例子:

<?php
interface Y { }

class X
{
    public function __construct(Y $x, $y=null)
    {

    }
}

$ref = new \ReflectionClass('X');

$c = $ref->getConstructor();
foreach ($c->getParameters() as $p) {
    var_dump($p->getClass());
}

输出:

class ReflectionClass#5 (1) {
  public $name =>
  string(1) "Y"
}
NULL

Silex 的 ControllerResolver有一个很好的例子说明你可以如何使用它:

<?php
// $params is an array of ReflectionParameter instances
protected function doGetArguments(Request $request, $controller, array $parameters)
{
    foreach ($parameters as $param) {
        // check to see if there's a class and if there is, see if the app property
        // is the same type. If so, set the attribute on the request
        if ($param->getClass() && $param->getClass()->isInstance($this->app)) {
            $request->attributes->set($param->getName(), $this->app);

            break;
        }
    }

    return parent::doGetArguments($request, $controller, $parameters);
}

关于php - 从php构造函数获取构造参数依赖,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19860715/

相关文章:

C# String.Format 可选参数

delphi - 将 Delphi 字符串作为参数发送给 DLL

java 类实例变量和构造函数的问题

php - 如何将错误和警告记录到文件中?

c# - 确定方法参数的上下文

php - 使用php从mysql数据库中的数组中提取特定数据

php - 我可以强制子类使用父类的构造函数吗?

java - 为什么 super() 构造函数不采用与父构造函数相同的参数?

php - 有没有办法让 mysqli_fetch_assoc() 在为空时打印没有数据?

php - 如何平均每 100 个 block 的数组