php反射類 ReflectionClass

來源:互聯網
上載者:User

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

  舉個例子:

  class fuc { //定義一個類

  static function ec() {

  echo '我是一個類';

  }

  }

  $class=new ReflectionClass('fuc'); //建立 fuc這個類的反射類

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

  Class [ class A ] { @@ F:phpwebmyPHPtest.php 23-30 - Constants [0] { } - Static properties [0] { } - Static methods [0] { } - Properties [0] { } - Methods [1] { Method [ public method __construct ] { @@ F:phpwebmyPHPtest.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;

  }

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.