使用 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/