(转载)php反射类 ReflectionClass

(转载)http://hi.baidu.com/daihui98/item/a67dfb8213055dd75f0ec165 

什么是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 方法


上面的过程很熟悉吧。其实和调用对象的方法类似
只不过这里是反着来的,方法在前,对象在后 

 

举例

[php]
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;  
    }  


 

 

posted @ 2013-06-17 10:25  robotke1  阅读(257)  评论(0编辑  收藏  举报