Home > Backend Development > PHP Tutorial > ReflectionClass:PHP中的反照类

ReflectionClass:PHP中的反照类

WBOY
Release: 2016-06-13 13:01:49
Original
776 people have browsed it

ReflectionClass: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('getArticles');
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);
//plugin.php 代码如下
class MycoolPugin implements Iplugin {
public static function getName(){
return 'MycoolPlugin';
}
public static function getMenuItems(){
return array(array('description'=>'MycoolPlugin','link'=>'/MyCoolPlugin'));
}
public static function getArticles(){
return array(array('path'=>'/MycoolPlugin','title'=>'This is a really cool article','text'=>xxxxxxxxx));
}
}上述代码是php反射类的一个应用。
什么是php反射类,顾名思义,可以理解为一个类的映射。
举个例子:

class fuc {        //定义一个类
static function ec() {
echo '我是一个类';
}
}
$class=new ReflectionClass('fuc');    //建立 fuc这个类的反射类
至于$class 这反射类里有什么东东,可以查看手册,这里不详解了

$fuc=$class->newInstance();  //相当于实例化 fuc 类
$fuc->ec(); //执行 fuc 里的方法ec

其中还有一些更高级的用法

$ec=$class->getmethod('ec');  //获取fuc 类中的ec方法
$fuc=$class->newInstance();  //实例化
$ec->invoke($fuc);      //执行ec 方法
上面的过程很熟悉吧。其实和调用对象的方法类似
只不过这里是反着来的,方法在前,对象在后

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template