2

Использование php ReflectionClass Я могу найти, какие параметры мне нужно вводить в конструкторе класса, чтобы создать новый экземпляр.Получить зависимость параметра конструкции от функции построения php

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

Есть ли способ получить зависимости этих параметров. Так что, если конструктор someClass выглядит следующим образом:

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

Могу ли я каким-то образом получить класс Завис из конструктора функции?

ответ

4

ReflectionMethod::getParameters возвращает массив из ReflectionParameter объектов. ReflectionParameters имеют метод, называемый getClass, который будет возвращать информацию о типе ключа param.

Пример:

<?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); 
} 
+0

Спасибо Я был почти там, но ваш последний толчок был именно тем, что мне нужно. 'GetClass()' в параметре выполнил задание! – Wilt