• Laravel 之 反射


    PHP 反射是程序实现依赖注入的基础,也是Laravel服务容器实现服务解析的基础

    反射函数参考:

    • ReflectionClass 报告了一个类的有关信息
    • ReflectionClass::getConstructor — 获取类的构造函数
    • ReflectionClass::getConstructor::getParameters — 获取到Constructor的属性值
    • ReflectionClass::newInstanceArgs — 从给出的参数创建一个新的类实例。
    • ReflectionParameter::getClass — 获得类型提示类。
    • ReflectionParameter::isDefaultValueAvailable — 检查是否有默认值。
    • ReflectionParameter::getDefaultValue — 获取到默认的属性值
    <?php
    
    class MyReflection
    {
        public function make(string $className): object
        {
            try{
                //反射传递的类
                $reflectionClass = new ReflectionClass($className);
                //获取到反射类的construct方法
                $constructor = $reflectionClass->getConstructor();
                //定义一个默认的依赖属性
                $dependent = [];
    
                //判断这个类是否存在construct函数
                if (!is_null($constructor)){
                    //获取到construct的属性
                    $parameters = $constructor->getParameters();
                    //获取到属性对应的类的属性...(递归)
                    $dependent = $this->handle($parameters);
                }
    
                //根据获取到属性,实例化这个类
                return $reflectionClass->newInstanceArgs($dependent);
            }catch (Exception $exception){
                throw new Exception($className. '未定义');
            }
        }
        
        public function handle(array $parameters): array
        {
            //定义一个默认的依赖属性数组
            $dependent = [];
    
            //获取到construct的参数,循环遍历
            foreach ($parameters as $parameter){
                //判断属性是否是类
                if ($parameter->getClass()){
                    //递归遍历,获取到依赖属性
                    $dependent[] = $this->make($parameter->getClass()->name);
                } else {
                    //判断是否存在默认值
                    if ($parameter->isDefaultValueAvailable()){
                        //存在默认值的,将值添加到依赖数组中
                        $dependent[] = $parameter->getDefaultValue();
                    } else {
                       	//可以根据类型判断,添加自己的参数
                        $dependent[] = '';
                    }
                }
            }
    
            return $dependent;
        }
    }
    
  • 相关阅读:
    服务器出现大量的127.0.0.1:3306 TIME_WAIT连接 解决方法 [转载]
    phpize安装php扩展CURL
    linux位数查看
    Linux下Sublime Text 3的安装
    ECstore后台报表显示空白问题解决办法
    centos 上安装phpstorm
    Nginx禁止目录执行php文件权限
    vue 动画
    vue的路由
    组件的传值 组件之间的通讯
  • 原文地址:https://www.cnblogs.com/ywjcqq/p/14848848.html
Copyright © 2020-2023  润新知