What is reflection?
The object in PHP's object-oriented programming is given the ability to introspect by the system, and this introspection process is called reflection.
Our intuitive understanding of reflection can be the process of finding the departure point and source based on the arrival point. In layman's terms, I give you a bare object. After that, you can know it based on this object. The class it belongs to and what methods it has.
In PHP, reflection refers to extending the analysis of PHP programs in the running state of PHP, exporting or extracting detailed information about classes, properties, methods, parameters, etc., including comments. This function of dynamically obtaining information and dynamically calling object methods is called reflection API.
Let’s experience it through a piece of code:
class person{ public $name; public $age; public function say() { echo $this->name."<br>".$this->age; } public function set($name,$value) { echo 'set name to value'; $this->$name = $value; } public function get($name) { if(!isset($this->$name)){ echo 'unset name'; $this->$name = 'seting~~~'; } return $this->$name; } } $stu = new person(); $stu->name = 'luyaran'; $stu->age = 26; $stu->sex = 'girl';
The above code is a simple class. We instantiate it and assign values to let It has meaning.
After that, let’s get a list of methods and properties of this stu object through the reflection API:
//获取对象的属性列表 $reflect = new ReflectionObject($stu); $props = $reflect->getProperties(); foreach ($props as $key_p => $value_p) { var_dump($value_p->getName()); } //获取对象的方法列表 $method = $reflect->getMethods(); foreach ($method as $key_m => $value_m) { var_dump($value_m->getName()); }
At the same time, reflection can be used not only for classes and objects, but also for functions. , extension modules, exceptions, etc.
As for us, we won’t go into details here. In the last bit of space, let’s talk about some functions of reflection.
First of all, it can be used for document generation, so we can use it to scan the classes in the document and generate scanned documents one by one.
Reflection can detect the internal structure of a class, can also be used as a hook to implement plug-in functions, and can also be used as a dynamic proxy.
The above is the detailed content of The principle of php reflection. For more information, please follow other related articles on the PHP Chinese website!