


The use of php reflection classes and the introduction of Laravel's use of reflection
Oct 08, 2018 pm 03:22 PM本篇文章给大家带来的内容是关于php反射类的使用及Laravel对反射的使用介绍,有一定的参考价值,有需要的朋友可以参考一下,希望对你有所帮助。
前言
PHP的反射类与实例化对象作用相反,实例化是调用封装类中的方法、成员,而反射类则是拆封类中的所有方法、成员变量,并包括私有方法等。就如“解刨”一样,我们可以调用任何关键字修饰的方法、成员。当然在正常业务中是建议不使用,比较反射类已经摒弃了封装的概念。
本章讲解反射类的使用及Laravel对反射的使用。
反射
反射类是PHP内部类,无需加载即可使用,你可以通过实例化 ReflectionClass
类去使用它。
方法
这里列举下PHP反射类常用的方法
方法名 | 注释 |
---|---|
ReflectionClass::getConstant | 获取定义过的一个常量 |
ReflectionClass::getConstants | 获取一组常量 |
ReflectionClass::getConstructor | 获取类的构造函数 |
ReflectionClass::getDefaultProperties | 获取默认属性 |
ReflectionClass::getDocComment | 获取文档注释 |
ReflectionClass::getEndLine | 获取最后一行的行数 |
ReflectionClass::getFileName | 获取定义类的文件名 |
ReflectionClass::getInterfaceNames | 获取接口(interface)名称 |
ReflectionClass::getMethods | 获取方法的数组 |
ReflectionClass::getModifiers | 获取类的修饰符 |
ReflectionClass::getName | 获取类名 |
ReflectionClass::getNamespaceName | 获取命名空间的名称 |
ReflectionClass::getParentClass | 获取父类 |
等等等等.... 所有关于类的方法、属性及其继承的父类、实现的接口都可以查询到。
详细文档请参考官网
栗子
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
|
输出结果
1 2 3 4 5 6 7 8 9 |
|
Laravel
Laravel在实现服务容器加载时使用了反射类。现在我们开启“解刨”模式
入口文件
index.php
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 |
|
是引用语句发生的下一行调用了make方法。各位很清楚,make方法用于解析类,所有make方法的实现一定是在引用的文件内。
bootstrap\app.php
1 2 3 |
|
laravel开始加载它的核心类,所有的实现从 Illuminate\Foundation\Application
开始。
Illuminate\Foundation\Application
1 2 3 4 5 6 7 8 9 10 |
|
在核心类中你可能准确的查找到make方法的存在,它加载了服务提供者随后调用了父类的方法make,要知道作为独立的模块 “服务容器”是绝对不能写在核心类的。懂点设计模式的都很清楚。
Illuminate\Container\Container
以 $api = $this->app->make('HelpSpot\API',['id'=>1]);
为例来讲解
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 |
|
可见一个服务容器就加载成功了。
The above is the detailed content of The use of php reflection classes and the introduction of Laravel's use of reflection. For more information, please follow other related articles on the PHP Chinese website!

Hot Article

Hot tools Tags

Hot Article

Hot Article Tags

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

11 Best PHP URL Shortener Scripts (Free and Premium)

Working with Flash Session Data in Laravel

Simplified HTTP Response Mocking in Laravel Tests

Build a React App With a Laravel Back End: Part 2, React

cURL in PHP: How to Use the PHP cURL Extension in REST APIs

12 Best PHP Chat Scripts on CodeCanyon

Announcement of 2025 PHP Situation Survey
