本篇文章是對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>