什么是php反射類,顧名思義,可以理解為一個(gè)類的映射。
舉個(gè)例子:
class fuc { //定義一個(gè)類
static function ec() {
echo '我是一個(gè)類';
}
}
$class=new ReflectionClass('fuc'); //建立 fuc這個(gè)類的反射類
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(); //相當(dāng)于實(shí)例化 fuc 類
$fuc->ec(); //執(zhí)行 fuc 里的方法ec
/*最后輸出:我是一個(gè)類*/
其中還有一些更高級的用法
$ec=$class->getmethod('ec'); //獲取fuc 類中的ec方法
$fuc=$class->newInstance(); //實(shí)例化
$ec->invoke($fuc); //執(zhí)行ec 方法
上面的過程很熟悉吧。其實(shí)和調(diào)用對象的方法類似
只不過這里是反著來的,方法在前,對象在后
舉例
try{
//如果存在控制器名字的類
if(class_exists($this->getController())) {
//利用反射api構(gòu)造一個(gè)控制器類對應(yīng)的反射類
$rc = new ReflectionClass($this->getController());
//如果該類實(shí)現(xiàn) 了IController接口
if($rc->implementsInterface('IController')) {
//該類擁有解析后的action字符串所指向的方法名
if($rc->hasMethod($this->getAction())) {
//構(gòu)造一個(gè)控制器類的實(shí)例
$controller = $rc->newInstance();
//獲取該類$action參數(shù)所指向的方法對象
$method = $rc->getMethod($this->getAction());
//反射類方法對象的調(diào)用方式:
$method->invoke($controller);
} else {
//以下為可能拋出異常
throw new Exception("Action");
}
} else {
throw new Exception("Interface");
}
} else {
throw new Exception("Controller");
}
}catch(exception $e)
{
echo $e;
}
轉(zhuǎn)載于:
http://blog.csdn.net/21aspnet/article/details/6952432