Speaking of the reflection API, I feel that the reflection API in PHP is similar to the Java.lang.reflect package in Java, which consists of a set of built-in classes that can print and parse class member properties and methods. You may have learned about object functions such as: Get_class_vars () but using the reflection API will be more flexible and the output information will be more detailed.
The first thing we need to know is that the reflection API is not just for checking classes, it includes a set of classes that are used to perform various functions: Common classes are as follows:
| Reflection class |
The basic information of the class can be printed (via the supplied static export () function) |
| Reflectionmethod class |
To be known, to print a method of a class, to obtain specific information about a method, etc. |
| Reflectionclass class |
Used to get class information, such as how to get a class containing the method, the class of the property, is not abstract class, etc. |
| Reflectionparameter class |
Display parameter information, you can dynamically get the parameters of the known method |
| Reflectionexception class |
Used to display error messages |
| Reflectionextension class |
The extension information of PHP can be used to determine whether the extension exists, etc. |
Span style= "FONT-SIZE:15PX; Font-family:microsoft Yahei; " > Below is a parameter program that I wrote myself to demonstrate the use of reflection:
<?phpclass person{//Member properties public $name; Public $age; Construction method Public Function construct ($name, $age) {$this->name = $name; $this->age = $age; }//member method public function Set_name ($name) {$this, $name = $name; } public Function Get_name () {return $this, $name; } public Function Get_age () {return $this, $age; Public Function Get_user_info () {$info = ' name: '. $this->name; $info. = ' Age: '. $this->age; return $info; }}class Teacher extends person{private $salary = 0; Public function construct ($name, $age, $salary) {parent::construct ($name, $age); $this->salary = $salary; } public Function Get_salary () {return $this, $salary; Public Function Get_user_info () {$info = Parent::get_user_info (); $info. = "Wages:". $this->salary; return $info; }}class Student extends Person{private $score = 0; Public function construct ($name, $age, $score) {parent::construct ($name, $age); $this->score = $score; } public Function Get_score () {return $this->score; Public Function Get_user_info () {$info = Parent::get_user_info (); $info. = "Score:". $this->score; return $info; }}header ("CONTENT-TYPE:TEXT/HTML;CHARSET=UTF8;"); $te _obj = new Teacher (' Miss Li ', ' 80 ', ' + '), $te _info = $te _obj->get_user_info (); $st _obj = new Student (' xiaoming ', ' 13 ', ' '); $st _info = $st _obj->get_user_info ();
We first use Var_dump (); Print the information of the class, as shown below, can see that just print out the simple information of the class, even the method is not, so from this information does not show the other swimming information.
Var_dump ($te _obj);
Object (Teacher) #1 (3) { ["salary": "Teacher":p rivate]=> string (4) " ["] ["Name"]=> string (9 ) "Miss Li" ["Age"]=> string (2) "36"}
Reflection::export ($obj);
We use the built-in method provided by reflection to print information as follows:
The printed information is more complete, including the member properties, member methods, basic information of the class, file path, method information, method properties, the parameters of the file, the number of rows and so on. A more comprehensive display of the class information. You can see that var_dump () or print_r can only display the class's brief information, a lot of information is not displayed at all, so they can only do simple debugging, the reflection API provides the class more information, can help us to know the invocation of the class situation, which to write interface, In particular, the invocation of other people's interface provides great convenience. If something is wrong, you can also help with debugging.
Object (Teacher) #1 (3) { ["salary": "Teacher":p rivate]=> string (4) " ["] ["Name"]=> string (9 "Miss Li" ["Age"]=> string (2) "}class" [Class person ] {@@/usr/local/www/phptest/oop/ reflaction.php 3-38 -Constants [0] { } -static properties [0] { } -static methods [0] {} -Properties [2] {property [public $name] property [public $age] } -Methods [5] {
method [public Method construct] {@@/usr/local/www/phptest/oop/reflaction.php 10-14 -Parameters [2 ] { Parameter #0 [ $name] .....
Specific use of the reflection API:
See the framework of the source of the students know that the framework can be loaded third-party plug-ins, class libraries and so on. In this example, we use the reflection API to simply implement this function, the prototype is I learned from the book, I understand the following in accordance with their own ideas to write a set: To achieve the function: a class to dynamic traversal Call Property class object, class can freely load other classes of methods, Instead of embedding the class into the existing code, you do not have to call the class library code manually.
Conventions: Each class must contain a work method, which can abstract an interface. You can put the information for each class in a file, equivalent to each class library information, the corresponding object of the property class library saved by the class, and then invoke the work method of each class library.
Here is the base code:
/* Attribute Interface */interface property{ function work ();} Class person{public $name; Public function construct ($name) { $this->name = $name; }} Class Studentcontroller implements property{ //set method, but requires person object parameter public function Setperson (person $obj _ person) { echo ' Student '. $obj _person->name; } Work method Simple implementation public function work () { echo ' student working! '; }} Class Enginecontroller implements property{ //set method public function Setweight ($weight) { echo ' This is engine, set weight '; } Public Function Setprice ($price) { echo ' This is engine, set price '; } Work method Simple implementation public function work () { echo ' engine working! '; }}
This defines two similar classes to implement the property interface, while all the simple implementation of the work () method Studentcontroller class slightly different, parameters need person object, and we can use the file to save the information of each class, we can also use member properties instead.
Class run{public static $mod _arr = []; public static $config = [' studentcontroller ' + = [' person ' = ' Xiao Ming '], ' engin Econtroller ' + [' weight ' = ' 500kg ', ' price ' = ' 4000 ']; Load Initialize public function construct () {$config = self:: $config; Used to check whether the implementation class $property = new Reflectionclass (' property '); foreach ($config as $class _name = + $params) {$class _reflect = new Reflectionclass ($class _name); if (! $class _reflect->issubclassof ($property)) {//Use the IsSubclassOf method to check if this object is the echo ' this is error '; Continue }//Get information about the class $class _obj = $class _reflect->newinstance (); $class _method = $class _reflect->getmethods (); foreach ($class _method as $method _name) {$this->handle_method ($class _obj, $method _name, $params); } array_push (self:: $mod _arr, $class _obj); }}//processing method calls Public function Handle_method (property $class _obj, Reflectionmethod $method _name, $params) { $m _name = $method _name->getname (); $args = $method _name->getparameters (); if (count ($args)! = 1 | | substr ($m _name, 0, 3)! = ' Set ') {return false; }//Case conversion, do fault-tolerant processing $property = Strtolower (substr ($m _name, 3)); if (!isset ($params [$property])) {return false; } $args _class = $args [0]->getclass (); Echo ' <pre> '; if (Empty ($args _class)) {$method _name->invoke ($class _obj, $params [$property]);//If the resulting class is empty proof that the underlying type argument needs to be passed } else {$method _name->invoke ($class _obj, $args _class->newinstance ($params [$property])), or//if no NULL description is required to pass the real Object}}}//program starts new Run ();
At the end of the program, run startup automatically calls the construction method, initializing the other member properties to load the class library, including initializing and performing the corresponding method operation, where the corresponding set method is completed. Where $mod the _arr property holds all the objects that call the class, each containing data that can traverse the contained object to invoke the work () method.
program only to do auxiliary understanding of the reflection Pai, each function is not perfect, the inside used a lot of reflection API class, methods, the following will be a summary of each method.
Common classes and functions provided by the reflection API :
The functions provided below are commonly used functions, not all, some functions are not used at all, so we have to lie that write, want to see the whole can be searched online, more. This set of methods provided does not need to be memorized and can be viewed when used.
1:reflection public static export (Reflector R [, BOOL Return])//Print the details of the class or method public static getmodifiernames (int modifiers )//Get modifier name 2:reflectionmethod:public static string export ()//print information for this method public mixed invoke ( Stdclass object, mixed* args)//Call the corresponding method public mixed Invokeargs (Stdclass object, array args)//Call the corresponding method, pass multi-parameter public BOOL IsFinal ()//Whether the method is final public bool IsAbstract ()//method is abstract public bool IsPublic ()//method is Public public bool IsPrivate ()//method is private public bool isprotected ()//method is protected public bool ISST Whether the atic ()//method is static public bool Isconstructor ()//method is a constructor 3:reflectionclass:public static string export () Print the details of the class public string getName ()//Gets the class name or interface name public bool IsInternal ()//class is internal to the System class public bool IsUs Erdefined ()//Whether the class is a user-defined class public bool isinstantiable ()//class is instantiated over public bool Hasmethod (string name)//class has a specific party French public bool HaspropErty (string name)//class has a specific property of public string GetFileName ()//Gets the file name that defines the class, including the path name public int getstartline () Gets the start line that defines the class public int getendline ()//Gets the end line that defines the class public string getdoccomment ()//Gets the comment p of the class Ublic Reflectionmethod GetConstructor ()//Get constructor information for this class public Reflectionmethod GetMethod (string name)//Get A specific method of the class information public reflectionmethod[] GetMethods ()//Get all the method information for the class public Reflectionproperty GetProperty (string name)//Get a specific property information public reflectionproperty[] getProperties ()//Get all property information for the class public array Getconstan TS ()//Get all constant information for this class public mixed getconstant (string name)//Get the class specific constant information public REFL Ectionclass[] Getinterfaces ()//Get interface class Information public bool Isinterface ()//test whether the class is an interface public bool IsAbstract () Tests whether the class is abstract class 4:reflectionparameter:public static string Export ()//export details of this parameter public string GetName () Get parameter name public bool ISpassedbyreference ()///test whether the parameter is passed by reference public Reflectionclass getclass ()//If the parameter is an object, return the class name of the object public bool IsArray () Tests whether this parameter is an array type public bool Allowsnull ()//test if the parameter is allowed to be empty public bool isoptional ()//test if the parameter Optional public bool Isdefaultvalueavailable ()///test if the parameter is the default parameter public mixed Getdefaultvalue ()///Get the default of this parameter when there is a default parameter available Value 5:reflectionextension class public static export ()//export all information for the extension public string getName ()//Get the name of the extension public stri ng getversion ()//Get the version of the extension public reflectionfunction[] getfunctions ()//Get all functions of the extension Public array getconstants ()// Get all constants for the extension public array getinientries ()//Get instruction information related to the extension in php.ini}