php反射类 ReflectionClass

来源:互联网 发布:去北大青鸟学java 编辑:程序博客网 时间:2024/04/30 14:40
什么是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;    }

 

原创粉丝点击