php反射類 ReflectionClass

來源:互聯網
上載者:User

標籤:style   blog   http   color   io   ar   strong   sp   div   

php反射類 ReflectionClass

什麼是php反射類,顧名思義,可以理解為一個類的映射。

舉個例子:

class fuc {        //定義一個類
static function ec() {
echo ‘我是一個類‘;
}
}
$class=new ReflectionClass(‘fuc‘);    //建立 fuc這個類的反射類


echo $class; //輸出這反射類

$fuc=$class->newInstance();  //相當於執行個體化 fuc 類
$fuc->ec(); //執行 fuc 裡的方法ec
/*最後輸出:我是一個類*/
其中還有一些更進階的用法

$ec=$class->getmethod(‘ec‘);  //擷取fuc 類中的ec方法
$fuc=$class->newInstance();  //執行個體化
$ec->invoke($fuc);      //執行ec 方法


上面的過程很熟悉吧。其實和調用對象的方法類似
只不過這裡是反著來的,方法在前,對象在後

 

舉例

[php] view plaincopy
    1. try{  
    2. //如果存在控制器名字的類  
    3. if(class_exists($this->getController())) {  
    4. //利用反射api構造一個控制器類對應的反射類  
    5. $rc = new ReflectionClass($this->getController());  
    6. //如果該類實現 了IController介面  
    7. if($rc->implementsInterface(‘IController‘)) {  
    8. //該類擁有解析後的action字串所指向的方法名  
    9. if($rc->hasMethod($this->getAction())) {  
    10. //構造一個控制器類的執行個體  
    11. $controller = $rc->newInstance();  
    12. //擷取該類$action參數所指向的方法對象  
    13. $method = $rc->getMethod($this->getAction());  
    14. //反射類方法對象的調用方式:  
    15. $method->invoke($controller);  
    16. } else {  
    17. //以下為可能拋出異常  
    18. throw new Exception("Action");  
    19. }  
    20. } else {  
    21. throw new Exception("Interface");  
    22. }  
    23. } else {  
    24. throw new Exception("Controller");  
    25. }  
    26.     }catch(exception $e)  
    27.     {  
    28.         echo $e;  
    29.     } 

php反射類 ReflectionClass

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.