亚洲乱码中文字幕综合,中国熟女仑乱hd,亚洲精品乱拍国产一区二区三区,一本大道卡一卡二卡三乱码全集资源,又粗又黄又硬又爽的免费视频

php 的反射詳解及示例代碼

 更新時(shí)間:2016年08月25日 15:44:03   作者:撣塵  
本文主要介紹PHP的反射內(nèi)容的知識(shí),這里提供相關(guān)的資料講解,及簡(jiǎn)單示例代碼供大家參考,有興趣的小伙伴可以參考下

 最近在看java編程思想,看到類型信息這一章,講到了類的信息以及反射的概念。順便溫故一下php的反射東西。手冊(cè)是這樣說(shuō)的:"PHP 5 具有完整的反射 API,添加了對(duì)類、接口、函數(shù)、方法和擴(kuò)展進(jìn)行反向工程的能力。 此外,反射 API 提供了方法來(lái)取出函數(shù)、類和方法中的文檔注釋。"當(dāng)然手冊(cè)上說(shuō)的有些抽象!所謂的逆向說(shuō)白就是能獲取關(guān)于類、方法、屬性、參數(shù)等的詳細(xì)信息,包括注釋! 文字總是那么枯燥,舉個(gè)例子

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 這個(gè)類返回時(shí)某個(gè)類的相關(guān)的信息,比如 屬性,方法,命名空間,實(shí)現(xiàn)那些接口等!上個(gè)例子中ReflectionClass:: getProperties 返回是 ReflectionProperty 對(duì)象的數(shù)組。

ReflectionProperty 類報(bào)告了類的屬性的相關(guān)信息。比如  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 是反是一個(gè) ReflectionMethod 類型 ,ReflectionMethod 類報(bào)告了一個(gè)方法的有關(guān)信息,比如 isAbstract isPrivate  isProtected isPublic isStatic   isConstructor,還有一個(gè)重要的方法Invoke,InvokeArgs 就是執(zhí)行方法!

其他的對(duì)象可以看看手冊(cè),不是很難!

那反射究竟有哪些用途?

反射是一個(gè)動(dòng)態(tài)運(yùn)行的概念,綜合使用他們可用來(lái)幫助我們分析其它類,接口,方法,屬性,方法和擴(kuò)展。還可構(gòu)建模式,比如動(dòng)態(tài)代理。在一些php框架中使用反射也是很經(jīng)常,比如kohana,yii,下面是kohana 的實(shí)現(xiàn)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);

上面的代碼可以清晰看到這個(gè)框架的流程!通過(guò)Router 其實(shí)就處理url的類,通過(guò)Router可以獲取哪個(gè)控制器、哪個(gè)方法!然后再執(zhí)行方法!

以上就是對(duì)PHP 反射的資料整理,后續(xù)繼續(xù)補(bǔ)充相關(guān)資料,謝謝大家對(duì)本站的支持!

相關(guān)文章

最新評(píng)論