> For the complete documentation index, see [llms.txt](https://xiaoxiami.gitbook.io/laravel/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://xiaoxiami.gitbook.io/laravel/laraval-yuan-ma-fen-xi/xiao-xi-jie/fan-she-ji-zhi.md).

# 反射机制

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

```php
<?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反射机制官方文档](http://php.net/manual/en/class.reflectionclass.php)

[PHP的反射机制](https://blog.csdn.net/hguisu/article/details/7357421)

[PHP 反射机制Reflection](https://www.cnblogs.com/nixi8/p/5176213.html)

[PHP反射机制实现自动依赖注入](https://blog.csdn.net/qq_20678155/article/details/70158374)
