php 的反射詳解及執行個體分析

來源:互聯網
上載者:User
本文主要介紹PHP的反射內容的知識,這裡提供相關的資料講解,及簡單範例程式碼供大家參考,有興趣的小夥伴可以參考下

 最近在看java編程思想,看到類型資訊這一章,講到了類的資訊以及反射的概念。順便溫故一下php的反射東西。手冊是這樣說的:"PHP 5 具有完整的反射 API,添加了對類、介面、函數、方法和擴充進行反向工程的能力。 此外,反射 API 提供了方法來取出函數、類和方法中的文檔注釋。"當然手冊上說的有些抽象!所謂的逆向說白就是能擷取關於類、方法、屬性、參數等的詳細資料,包括注釋! 文字總是那麼枯燥,舉個例子

class Foo {  public  $foo = 1;  protected $bar = 2;  private  $baz = 3;    /**   * Enter description here ...   */  public function myMethod()  {    echo 'hello 2b';  }}$ref = new ReflectionClass('Foo');$props = $ref->getProperties();foreach ($props as $value) {  echo $value->getName()."\n";}//output//foo //bar//baz

ReflectionClass 這個類返回時某個類的相關的資訊,比如 屬性,方法,命名空間,實現那些介面等!上個例子中ReflectionClass:: getProperties 返回是 ReflectionProperty 對象的數組。

ReflectionProperty 類報告了類的屬性的相關資訊。比如 isDefault isPrivate isProtected isPublic isStatic等,方法getName 是擷取屬性的名稱!

以上是擷取屬性的,還有擷取類方法的比如

class Foo {  public  $foo = 1;  protected $bar = 2;  private  $baz = 3;    /**   * Enter description here ...   */  public function myMethod()  {    echo 'hello 2b';  }}$ref = new ReflectionClass('Foo');$method = $ref->getMethod('myMethod');$method->invoke($ref->newInstance());

ReflectionClass::getMethod 是反是一個 ReflectionMethod 類型 ,ReflectionMethod 類報告了一個方法的有關資訊,比如 isAbstract isPrivate isProtected isPublic isStatic isConstructor,還有一個重要的方法Invoke,InvokeArgs 就是執行方法!

其他的對象可以看看手冊,不是很難!

那反射究竟有哪些用途?

反射是一個動態啟動並執行概念,綜合使用他們可用來協助我們分析其它類,介面,方法,屬性,方法和擴充。還可構建模式,比如動態代理。在一些php架構中使用反射也是很經常,比如kohana,yii,下面是kohana 的實現mvc的代碼,就是用到了反射!

// Start validation of the controller$class = new ReflectionClass(ucfirst(Router::$controller).'_Controller');// Create a new controller instance$controller = $class->newInstance();// Load the controller method$method = $class->getMethod(Router::$method);// Execute the controller method$method->invokeArgs($controller, $arguments);

上面的代碼可以清晰看到這個架構的流程!通過Router 其實就處理url的類,通過Router可以擷取哪個控制器、哪個方法!然後再執行方法!

總結:以上就是本篇文的全部內容,希望能對大家的學習有所協助。

聯繫我們

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