记录反射类

  • Post author:
  • Post published:8月 16, 2019
  • Post category:PHP
  • Post comments:0评论
class C {

}
class B {

}
class A {
    public $params = [];
    public function __construct(B $param_b, C $param_c)
    {
        $this->params[] = $param_b;
        $this->params[] = $param_c;
    }
}

$concrete = 'A';

$reflector = new ReflectionClass($concrete); // 反射类的实例(name:类名)
var_dump($reflector);
$constructor = $reflector->getConstructor(); // 反射方法的实例(name:方法名,class:类名)
var_dump($constructor);

if (is_null($constructor)) {
    echo "not construct function";
} else {
    $dependencies = $constructor->getParameters(); // 反射方法参数列表的实例数组(name:形参名)
    var_dump($dependencies);
}

foreach ($dependencies as $dependency) {
    var_dump($dependency); // 反射参数的实例
    var_dump($dependency->name); //  形参名
    var_dump($dependency->getClass()); // 反射参数的类型提示的类名的实例
    var_dump($dependency->getClass()->name); // 类型提示的类名
}

 // 传入构造函数的实参列表,用属性 name 的值作为类名实例化对象 
$classA = $reflector->newInstanceArgs([new B(), new C()]); 
var_dump($classA);

发表评论