ReflectionClass: Reflection class interfaceIplugin {publicstaticfunctiongetName ();} functionfindPlugins () {$ pluginsarray (); foreach (reflection () as $ class) {$ refle ReflectionClass: Reflection class in PHP
Interface Iplugin {
Public static function getName ();
}
Function findPlugins (){
$ Plugins = array ();
Foreach (get_declared_classes () as $ class ){
$ ReflectionClass = new ReflectionClass ($ class );
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 ('getarticle ');
If ($ reflectionMethod-> isStatic ()){
$ Items = $ reflectionMethod-> 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 );
// The plugin. php code is as follows:
Class MycoolPugin implements Iplugin {
Public static function getName (){
Return 'myolplugin ';
}
Public static function getMenuItems (){
Return array ('description' => 'myolin in', 'link' => '/mycoolin in '));
}
Public static function getArticles (){
Return array ('path' => '/mycoolin in', 'title' => 'This is a really cool article', 'text' => xxxxxxxxx ));
}
} The above code is an application of the php Reflection class.
What is a php Reflection class? as the name suggests, it can be understood as a class ING.
For example:
Class fuc {// define a class
Static function ec (){
Echo 'I am a class ';
}
}
$ Class = new ReflectionClass ('fuc'); // creates a reflection class for the fuc class.
For the reflection class $ class, you can view the manual. I will not explain it here.
$ Fuc = $ class-> newInstance (); // It is equivalent to instantiating the fuc class
$ Fuc-> ec (); // execute the method ec in fuc
There are some more advanced usage
$ Ec = $ class-> getmethod ('EC'); // Obtain the ec method in the fuc class
$ Fuc = $ class-> newInstance (); // instantiate
$ Ec-> invoke ($ fuc); // execute the ec method
The above process is quite familiar. In fact, it is similar to calling an object.
But here is the opposite, the method is in front, the object is in the back