什么是php反射类,顾名思义,能够理解为一个类的映射。

举个样例:


class fuc {        //定义一个类

static function ec() {

echo '我是一个类';

}

}

$class=new ReflectionClass('fuc');    //建立 fuc这个类的反射类


echo $class; //输出这反射类

Class [ class A ] { @@ F:\phpweb\myPHP\test.php 23-30 - Constants [0] { } - Static properties [0] { } - Static methods [0] { } - Properties [0] { } - Methods [1] { Method [ public method __construct ] { @@ F:\phpweb\myPHP\test.php 26 - 29 } } }



$fuc=$class->newInstance();  //相当于实例化 fuc 类

$fuc->ec(); //运行 fuc 里的方法ec

/*最后输出:我是一个类*/


当中另一些更高级的使用方法


$ec=$class->getmethod('ec');  //获取fuc 类中的ec方法

$fuc=$class->newInstance();  //实例化

$ec->invoke($fuc);      //运行ec 方法


上面的过程非常熟悉吧。事实上和调用对象的方法相似

仅仅只是这里是反着来的,方法在前,对象在后

 

举例

try{
//假设存在控制器名字的类
if(class_exists($this->getController())) {
//利用反射api构造一个控制器类相应的反射类
$rc = new ReflectionClass($this->getController());
//假设该类实现 了IController接口
if($rc->implementsInterface('IController')) {
//该类拥有解析后的action字符串所指向的方法名
if($rc->hasMethod($this->getAction())) {
//构造一个控制器类的实例
$controller = $rc->newInstance();
//获取该类$action參数所指向的方法对象
$method = $rc->getMethod($this->getAction());
//反射类方法对象的调用方式:
$method->invoke($controller);
} else {
//下面为可能抛出异常
throw new Exception("Action");
}
} else {
throw new Exception("Interface");
}
} else {
throw new Exception("Controller");
}
}catch(exception $e)
{
echo $e;
}