反射机制

可以参考以下列出来的资料,理解一下通过反射机制来实例化,laravel的核心Ioc容器就采用了的这种思想。

<?php
class Person {  
    /** 
     * For the sake of demonstration, we"re setting this private
     */ 
    private $_allowDynamicAttributes = false;

    /** type=primary_autoincrement */
    protected $id = 0;

    /** type=varchar length=255 null */
    protected $name;

    /** type=text null */
    protected $biography;

        public function getId()
        {
            return $this->id;
        }
        public function setId($v)
        {
               $this->id = $v;
        }
        public function getName()
        {
               return $this->name;
        }
        public function setName($v)
        {
             $this->name = $v;
        }
        public function getBiography()
        {
              return $this->biography;
        }
        public function setBiography($v)
        {
             $this->biography = $v;
        }
}


$class = new ReflectionClass('Person');//建立 Person这个类的反射类
if(!$class->isInstantiable()) { //检查类是否可实例化
    echo 'Target class is not instantiable.';
    exit;
}

$constructor = $class->getConstructor(); // 获取类的构造函数,没有则返回null
if(is_null($constructor)){
   // new Person;  // 可以直接new实现实例化
}

$dependencies = $constructor->getParameters(); //获取参数
//$args = $this->getDependencies($dependencies)  解决通过反射机制实例化对象时的依赖
$instance  = $class->newInstanceArgs($args);//相当于实例化Person 类

资料

reflectionclass反射机制官方文档

PHP的反射机制

PHP 反射机制Reflection

PHP反射机制实现自动依赖注入

Last updated

Was this helpful?