How to implement reflective injection in php interview
PHP has a complete reflection API, providing the ability to reverse engineer classes, interfaces, functions, methods and extensions. Through the capabilities provided by class reflection, we can know how the class is defined, what attributes it has, what methods it has, what parameters the method has, what the path to the class file is, and other very important information. It is precisely because of class reflection that many PHP frameworks can implement dependency injection to automatically resolve the dependencies between classes, which brings great convenience to our daily development.
This article mainly explains how to use class reflection to implement dependency injection (Dependency Injection). It will not describe every API in PHP Reflection one by one. To better understand, let's look at class reflection through an example and how to implement dependency injection.
The following class represents a point in the coordinate system and has two attributes, the abscissa x and the ordinate y.
/** * Class Point */ class Point { public $x; public $y; /** * Point constructor. * @param int $x horizontal value of point's coordinate * @param int $y vertical value of point's coordinate */ public function __construct($x = 0, $y = 0) { $this->x = $x; $this->y = $y; } }
The next class represents a circle. You can see that there is a parameter in its constructor that is of the Point class, that is, the Circle class is dependent on the Point class.
class Circle { /** * @var int */ public $radius;//半径 /** * @var Point */ public $center;//圆心点 const PI = 3.14; public function __construct(Point $point, $radius = 1) { $this->center = $point; $this->radius = $radius; } //打印圆点的坐标 public function printCenter() { printf('center coordinate is (%d, %d)', $this->center->x, $this->center->y); } //计算圆形的面积 public function area() { return 3.14 * pow($this->radius, 2); } }
ReflectionClass
Next we use reflection to reverse engineer the Circle class. Pass the name of the Circle class to reflectionClass to instantiate an object of the ReflectionClass class.
$reflectionClass = new reflectionClass(Circle::class); //返回值如下 object(ReflectionClass)#1 (1) { ["name"]=> string(6) "Circle" }
Reflect the constants of the class
$reflectionClass->getConstants();
Return an associative array consisting of the constant name and value
array(1) { ["PI"]=> float(3.14) }
Get properties through reflection
$reflectionClass->getProperties();
Return an array composed of ReflectionProperty objects
array(2) { [0]=> object(ReflectionProperty)#2 (2) { ["name"]=> string(6) "radius" ["class"]=> string(6) "Circle" } [1]=> object(ReflectionProperty)#3 (2) { ["name"]=> string(6) "center" ["class"]=> string(6) "Circle" } }
Reflect out the methods defined in the class
$reflectionClass->getMethods();
Returns an array of ReflectionMethod objects
array(3) { [0]=> object(ReflectionMethod)#2 (2) { ["name"]=> string(11) "__construct" ["class"]=> string(6) "Circle" } [1]=> object(ReflectionMethod)#3 (2) { ["name"]=> string(11) "printCenter" ["class"]=> string(6) "Circle" } [2]=> object(ReflectionMethod)#4 (2) { ["name"]=> string(4) "area" ["class"]=> string(6) "Circle" } }
We can also obtain the constructor method of the class separately through getConstructor(), Its return value is a ReflectionMethod object.
$constructor = $reflectionClass->getConstructor();
Reflection method parameters
$parameters = $constructor->getParameters();
The return value is an array composed of ReflectionParameter objects.
array(2) { [0]=> object(ReflectionParameter)#3 (1) { ["name"]=> string(5) "point" } [1]=> object(ReflectionParameter)#4 (1) { ["name"]=> string(6) "radius" } }
Dependency Injection
Okay next we write a function named make, pass the class name to the make function and return the object of the class, in make Here it will help us inject the dependencies of the class, that is, in this case, it will help us inject the Point object into the constructor of the Circle class.
//构建类的对象 function make($className) { $reflectionClass = new ReflectionClass($className); $constructor = $reflectionClass->getConstructor(); $parameters = $constructor->getParameters(); $dependencies = getDependencies($parameters); return $reflectionClass->newInstanceArgs($dependencies); } //依赖解析 function getDependencies($parameters) { $dependencies = []; foreach($parameters as $parameter) { $dependency = $parameter->getClass(); if (is_null($dependency)) { if($parameter->isDefaultValueAvailable()) { $dependencies[] = $parameter->getDefaultValue(); } else { //不是可选参数的为了简单直接赋值为字符串0 //针对构造方法的必须参数这个情况 //laravel是通过service provider注册closure到IocContainer, //在closure里可以通过return new Class($param1, $param2)来返回类的实例 //然后在make时回调这个closure即可解析出对象 //具体细节我会在另一篇文章里面描述 $dependencies[] = '0'; } } else { //递归解析出依赖类的对象 $dependencies[] = make($parameter->getClass()->name); } } return $dependencies; }
After defining the make method, we use it to help us instantiate the object of the Circle class:
$circle = make('Circle'); $area = $circle->area(); /*var_dump($circle, $area); object(Circle)#6 (2) { ["radius"]=> int(1) ["center"]=> object(Point)#11 (2) { ["x"]=> int(0) ["y"]=> int(0) } } float(3.14)*/
Through the above In the example, I briefly described how to use the reflection of PHP classes to implement dependency injection. Laravel's dependency injection is also implemented through this idea, but the design is more sophisticated and makes extensive use of closure callbacks to deal with various complex dependency injections. .
Recommended tutorial: PHP video tutorial
The above is the detailed content of How to implement reflective injection in php interview. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

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



PHP 8.4 brings several new features, security improvements, and performance improvements with healthy amounts of feature deprecations and removals. This guide explains how to install PHP 8.4 or upgrade to PHP 8.4 on Ubuntu, Debian, or their derivati

Visual Studio Code, also known as VS Code, is a free source code editor — or integrated development environment (IDE) — available for all major operating systems. With a large collection of extensions for many programming languages, VS Code can be c

If you are an experienced PHP developer, you might have the feeling that you’ve been there and done that already.You have developed a significant number of applications, debugged millions of lines of code, and tweaked a bunch of scripts to achieve op

This tutorial demonstrates how to efficiently process XML documents using PHP. XML (eXtensible Markup Language) is a versatile text-based markup language designed for both human readability and machine parsing. It's commonly used for data storage an

JWT is an open standard based on JSON, used to securely transmit information between parties, mainly for identity authentication and information exchange. 1. JWT consists of three parts: Header, Payload and Signature. 2. The working principle of JWT includes three steps: generating JWT, verifying JWT and parsing Payload. 3. When using JWT for authentication in PHP, JWT can be generated and verified, and user role and permission information can be included in advanced usage. 4. Common errors include signature verification failure, token expiration, and payload oversized. Debugging skills include using debugging tools and logging. 5. Performance optimization and best practices include using appropriate signature algorithms, setting validity periods reasonably,

A string is a sequence of characters, including letters, numbers, and symbols. This tutorial will learn how to calculate the number of vowels in a given string in PHP using different methods. The vowels in English are a, e, i, o, u, and they can be uppercase or lowercase. What is a vowel? Vowels are alphabetic characters that represent a specific pronunciation. There are five vowels in English, including uppercase and lowercase: a, e, i, o, u Example 1 Input: String = "Tutorialspoint" Output: 6 explain The vowels in the string "Tutorialspoint" are u, o, i, a, o, i. There are 6 yuan in total

Static binding (static::) implements late static binding (LSB) in PHP, allowing calling classes to be referenced in static contexts rather than defining classes. 1) The parsing process is performed at runtime, 2) Look up the call class in the inheritance relationship, 3) It may bring performance overhead.

What are the magic methods of PHP? PHP's magic methods include: 1.\_\_construct, used to initialize objects; 2.\_\_destruct, used to clean up resources; 3.\_\_call, handle non-existent method calls; 4.\_\_get, implement dynamic attribute access; 5.\_\_set, implement dynamic attribute settings. These methods are automatically called in certain situations, improving code flexibility and efficiency.
