php中的反射是如何應用的?

來源:互聯網
上載者:User
本篇文章是對php中反射的應用進行了詳細的分析介紹,需要的朋友參考下

一 反射的使用:

<?phpclass Person{ public $name; function construct($name){  $this->name=$name; }}interface Module{ function execute();}class FtpModule implements Module{ function setHost($host){  print "FtpModule::setHost():$host\n"; } function setUser($user){  print "FtpModule::setUser():$user\n"; } function execute(){  //something }}class PersonModule implements Module{ function setPerson(Person $person){  print "PersonModule::setPerson:{$person->name}\n"; } function execute(){  //something }}class ModuleRunner{ private $configData        =array(          "PersonModule"=>array('person'=>'bob'),          "FtpModule"=>array('host'=>'example.com','user'=>'anon')        ); private $modules=array(); function init(){  $interface=new ReflectionClass('Module');  foreach($this->configData as $modulename=>$params){   $module_class=new ReflectionClass($modulename);//根據配置configData的名稱,執行個體化ReflectionClass   if(!$module_class->isSubclassOf($interface)){//檢查反射得到了類是否是$interface的子類    throw new Exception("unknown module type:$modulename");//不是Module子類則拋出異常   }   $module=$module_class->newInstance();//執行個體化一個FtpModule或者PersonModule對象   foreach($module_class->getMethods() as $method){//獲得類中的方法    $this->handleMethod($module,$method,$params);   }   array_push($this->modules,$module);//將執行個體化的module對象放入$modules數組中  } } function handleMethod(Module $module,ReflectionMethod $method,$params){  $name=$method->getName();//獲得方法名稱  $args=$method->getParameters();//獲得方法中的參數  if(count($args)!=1||substr($name,0,3)!="set"){//檢查方法必須是以set開頭,且只有一個參數   return false;  }  $property=strtolower(substr($name,3));//講方法名去掉set三個字母,作為參數  if(!isset($params[$property])){//如果$params數組不包含某個屬性,就返回false   return false;  }  $arg_class=@$args[0]->getClass;//檢查setter方法的第一個參數(且唯一)的資料類型  if(empty($arg_class)){   $method->invoke($module,$params[$property]);  }else{   $method->invoke($module,$arg_class->newInstance($params[$property]));  } }}$test=new ModuleRunner();$test->init();?>


二 通過反射獲得類中資訊:

<PRE class=php name="code"><?phpclass ReflectionUtil{ static function getClassSource(ReflectionClass $class){  $path=$class->getFileName();  $lines=@file($path);  $from=$class->getStartLine();  $to=$class->getEndLine();  $len=$to-$from+1;  return implode(array_slice($lines,$from-1,$len)); }}$classname="Person";$path="../practice/{$classname}.php";if(!file_exists($path)){  throw new Exception("No such file as {$path}");}require_once($path);if(!class_exists($classname)){ throw new Exception("No such class as {$classname}");}print ReflectionUtil::getClassSource(new ReflectionClass('Person'));?></PRE><BR><PRE></PRE>結果是:class Person{ public $age; public $name; function getName(){return "zjx";} function getAge(){return 12;} function toString(){ $rs=$this->getName(); $rs.="(age".$this->getAge().")"; return $rs; } }<PRE></PRE><PRE></PRE><PRE></PRE><PRE></PRE>

聯繫我們

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