laravel 笔记
  • Introduction
  • 说明
  • Laravel 基础
    • 安装与配置
    • 目录结构
    • 路由配置
    • MVC 配置
    • 数据库操作
      • DB façade 方式
      • 查询构造器方式
      • Eloquent ORM 方式
      • 数据库迁移
      • 数据填充
    • 请求和响应和重定向
    • Session
    • 中间件
    • 其他
      • Artisan 命令行
  • Laraval 源码分析
    • 请求到响应的生命周期
      • 程序启动准备
      • 请求实例化
      • 处理请求
      • 响应的发送与程序终止
    • 路由
    • 补充知识点
      • 反射机制
      • Closure 类
  • 资料
  • 核心思想
    • 服务容器
    • 服务提供者
    • Facades(门脸模式)
  • 开发笔记
  • Artisan 命令
  • yarn
Powered by GitBook
On this page

Was this helpful?

  1. Laraval 源码分析
  2. 补充知识点

反射机制

可以参考以下列出来的资料,理解一下通过反射机制来实例化,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 类

资料

Previous补充知识点NextClosure 类

Last updated 5 years ago

Was this helpful?

reflectionclass反射机制官方文档
PHP的反射机制
PHP 反射机制Reflection
PHP反射机制实现自动依赖注入