A detailed explanation of the PHP reflection mechanism and the plugin architecture example

Source: Internet
Author: User
Tags php class reflector
1. Use:
The extension parses the PHP program, exporting or extracting detailed information about classes, methods, properties, parameters, and so on, including comments.
Reflection can be said to be an extension of the PHP library function: "Classes/objects class/Object function".
Mainly used in the program to detect the existing PHP procedures within the class, methods and other information, and make processing.

2. API Overview:

Class Reflection {}interface Reflector {}class reflectionexception extends Exception {}class reflectionfunction impleme NTS Reflector {}class Reflectionparameter implements Reflector {}class Reflectionmethod extends Reflectionfunction {}CL Reflectionclass implements Reflector {}class Reflectionobject extends Reflectionclass {}class Reflectionproperty imp Lements Reflector {}class reflectionextension implements Reflector {}

3. Detailed Description: (See the PHP Manual for examples)
①reflection class

<?phpclass reflection{public    static mixed export (Reflector R [, BOOL Return])    //export details of a class or method public    Static array getmodifiernames (int modifiers)    //Gets the name of the modifier}?>

②reflectionexception class

The class inherits from the standard class and has no special methods and properties.

③reflectionfunction class

<?phpclass Reflectionfunction implements reflector{final Private clone () PU Blic object Construct (string name) public string toString () public static string export ()//export details of the function public    String GetName ()//Get Function name public bool IsInternal ()//test whether the system intrinsics public bool isuserdefined ()//test is a user-defined function    public string GetFileName ()//Gets the file name, including the path name public int getstartline ()//Gets the starting line of the definition function public int getendline () Gets the end line of the defined function public string getdoccomment ()//Gets the comment of the function public array getstaticvariables ()//Get Static variable public mix Ed Invoke (mixed* args)//Call the function, pass the parameter list parameter public mixed Invokeargs (array args)//Call the function, pass the parameter public bool Retur Nsreference ()///test whether the function returns a reference public reflectionparameter[] GetParameters ()//The parameter required to get the method, the return value is an object array public int GETN Umberofparameters ()///The number of arguments required to obtain the method public int getnumberofrequiredparameters ()////The number of arguments required to obtain the method}?> 

④reflectionparameter class:

<?phpclass Reflectionparameter implements reflector{    final private clone () public    object Construct (string Name) public    string toString () public    static string export ()    //export details of this parameter public    string GetName ()    //Get the 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 ()    //test whether the parameter is an array type public    bool Allowsnull ()    // Tests whether this parameter is allowed to be empty public    bool Isoptional ()    //test if the parameter is optional, public    bool Isdefaultvalueavailable () when there are default parameters    //Test whether the parameter is the default parameter public    mixed Getdefaultvalue ()    //Gets the default value for this parameter}?>

⑤reflectionclass class:

<?phpclass Reflectionclass implements reflector{final private clone () public object construct (string name) Pu Blic string toString () public static string export ()//exports the details of the class public string getName ()//Get class name or interface name public BOOL IsInternal ()//test whether the class is a system internal class public bool isuserdefined ()//test whether the class is a user-defined class public bool isinstantiable ()/ /test whether the class is instantiated public bool HasConstant (string name)///test whether the class has a specific constant public bool Hasmethod (string name)//test If the class has a special Fixed method public bool Hasproperty (string name)//test If the class has a specific property of public string GetFileName ()//Gets the file name that defines the class, including the path name pub LIC int getstartline ()//Gets the start line of the class that defines the public int getendline ()//Gets the end line that defines the class public string getdoccomment ()//Get The comment public reflectionmethod getconstructor ()//Gets the constructor information for the class public Reflectionmethod GetMethod (string name)//  Obtain information about a particular method of the class public reflectionmethod[] GetMethods ()//Get all the method information for the class public Reflectionproperty GetProperty (string Name)//Get a specific attribute information   Public reflectionproperty[] GetProperties ()//Get all property information for this class public array getconstants ()//Get all constant information for this class public m Ixed getconstant (string name)///Get the class specific constant information public reflectionclass[] getinterfaces ()//Get interface class Information public bool IsIn Terface ()//test whether the class is an interface public bool IsAbstract ()//test whether the class is abstract class public bool IsFinal ()//test whether the class is declared final Publi c int GetModifiers ()//Gets the modifier for the class, the return value type may be a resource type//further read by Reflection::getmodifiernames ($class->getmodifiers ()) PU blic bool Isinstance (Stdclass object)//test whether the incoming object is an instance of the class public Stdclass newinstance (mixed* args)//Create the class instance Pu    Blic reflectionclass Getparentclass ()//Get parent class public bool IsSubclassOf (Reflectionclass Class)//test whether the passed-in class is the parent class of the class    Public array getstaticproperties ()//Gets all static properties of the class public mixed Getstaticpropertyvalue (string name [, mixed default]) Gets the static property value of the class, if private, the public void Setstaticpropertyvalue (string name, mixed value)//sets the static property value of the class, if private, does not Accessible, contrary to encapsulation principle public arrAy getdefaultproperties ()//Get property information for this class, without static property public bool Isiterateable () public bool Implementsinterface (string n AME)//test whether a specific interface is implemented public reflectionextension getextension () public string getextensionname ()}?>

⑥reflectionmethod class:

<?phpclass Reflectionmethod extends reflectionfunction{public construct (mixed class, String name) public string    ToString () public static string export ()//Export the method's information public mixed invoke (Stdclass object, mixed* args)//Call the method Public mixed Invokeargs (Stdclass object, array args)//Call this method, pass multi-parameter public bool IsFinal ()//test whether the method is final pub LIC bool IsAbstract ()//test whether the method is abstract public bool IsPublic ()//test whether the method is public public bool IsPrivate ()// Tests whether the method is private public bool isprotected ()//tests whether the method is protected public bool IsStatic ()//tests whether the method is static Publi c bool Isconstructor ()//test whether the method is a constructor public bool Isdestructor ()//test whether the method is a destructor public int getmodifiers ()/ /Gets the modifier of the method public Reflectionclass Getdeclaringclass ()//Gets the class to which the method belongs//inherited from Reflectionfunction final p Rivate Clone () public string getName () public bool IsInternal () public bool isuserdefined () public string GETF Ilename () public intGetstartline () public int getendline () public string getdoccomment () public array getstaticvariables () public BOOL Returnsreference () public reflectionparameter[] GetParameters () public int getnumberofparameters () public in T Getnumberofrequiredparameters ()}?>

⑦reflectionproperty class:

<?phpclass Reflectionproperty implements reflector{    final private clone () public    construct (mixed class, String name) public    string toString () public    static string export ()    //export details of the property public    string GetName ()    //Get the property name public    bool IsPublic ()    //test if the property name is public public    bool IsPrivate ()    // Tests whether the property name is private public    bool isprotected ()    //test if the property name is protected public    bool IsStatic ()    // Tests whether the property name is static public    , BOOL IsDefault () public    int getmodifiers ()    //Get modifier public    mixed GetValue ( Stdclass object)    //Get the property value public    void SetValue (Stdclass object, mixed value)    //Set the property value    public Reflectionclass Getdeclaringclass ()    //Get the class public that defines the property the public    string getdoccomment ()    //Get a comment on the property}?>

⑧reflectionextension class

<?phpclass Reflectionextension implements Reflector {    final private clone () public    construct (string name) Public    A String toString () public    static string export ()    //Export all information for the extension public    string getName ()    // Gets the name of the extension public    string getversion ()    //Gets the version of the extension public    reflectionfunction[] getfunctions ()    // Get all the functions of the extension public    array getconstants ()    //Get all constants of the extension public    array getinientries ()    //Get related to the extension, Command information in php.ini public    reflectionclass[] getclasses () public    array getclassnames ()}?>

4. Report:

In fact, from the 2nd API overview can be seen: the interface is very useful.
On the one hand, the reflector interface provides a good interface naming specification for reflection small systems,
Every implementation of his class must be his norm, from the outside, the small system API is very uniform.
On the other hand, because many classes implement the Reflector interface,
In such a hierarchy, it is easy to achieve polymorphism.

PHP Reflection api--Plug-in system architecture using reflection technology

/** * @name PHP Reflection api--Plug-in system architecture implemented using reflection technology * @author:P hpcq.com */interface iplugin{public static F     Unction GetName ();                    } function Findplugins () {$plugins = array (); foreach (Get_declared_classes () as $class) {$reflectionClass = new Reflectionclass ($cl                                     ); if ($reflectionClass->implementsinterface (' Iplugin ')) {$plugins []                                     = $reflectionClass;      }} return $plugins;                     } function Computemenu () {$menu = array ();                                                     foreach (Findplugins () as $plugin) {if ($plugin->hasmethod (' Getmenuitems ')) {                                             $reflectionMethod = $plugin->getmethod (' Getmenuitems ');        if ($reflectionMethod->isstatic ()) {$items                                                    = $reflectionMethod->invoke (null);                                                                     } else {$pluginInstance = $plugin->newinstance (); $items = $reflectionMethod->invoke ($pluginInstance)                                                     ;                                     } $menu = Array_merge ($menu, $items);     }} return $menu;                     } function Computearticles () {$articles = array ();                                                    foreach (Findplugins () as $plugin) {if ($plugin->hasmethod (' getarticles ')) { $reflectionMethod = $plugin->getmethod ('Getarticles '); if ($reflectionMethod->isstatic ()) {$items = $refl                                                     Ectionmethod->invoke (NULL);                                                                     } else {$pluginInstance = $plugin->newinstance (); $items = $reflectionMethod->invoke ($pluginInstance)                                                     ;                                     } $articles = Array_merge ($articles, $items);     }} return $articles;     } require_once (' plugin.php ');     $menu = Computemenu ();     $articles = Computearticles ();     Print_r ($menu); Print_r ($articles);
//plugin.php code is as follows <?php class Mycoolpugin implements Iplugin {                     public static function GetName () {return ' mycoolplugin '; } public static function Getmenuitems () {return Array (' des                     Cription ' = ' mycoolplugin ', ' link ' = '/mycoolplugin '); The public static function Getarticles () {return array (' path ' =                     > '/mycoolplugin ', ' title ' = ' This is a really cool article ', ' Text ' =>xxxxxxxxx); }     }

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.