php中反射的應用舉例

來源:互聯網
上載者:User
  1. /**
  2. * php反射執行個體
  3. * edit bbs.it-home.org
  4. */
  5. class Person{
  6. public $name;
  7. function __construct($name){
  8. $this->name=$name;
  9. }
  10. }
  11. interface Module{
  12. function execute();
  13. }
  14. class FtpModule implements Module{
  15. function setHost($host){
  16. print "FtpModule::setHost():$host\n";
  17. }
  18. function setUser($user){
  19. print "FtpModule::setUser():$user\n";
  20. }
  21. function execute(){
  22. //something
  23. }
  24. }
  25. class PersonModule implements Module{
  26. function setPerson(Person $person){
  27. print "PersonModule::setPerson:{$person->name}\n";
  28. }
  29. function execute(){
  30. //something
  31. }
  32. }
  33. class ModuleRunner{
  34. private $configData
  35. =array(
  36. "PersonModule"=>array('person'=>'bob'),
  37. "FtpModule"=>array('host'=>'example.com','user'=>'anon')
  38. );
  39. private $modules=array();
  40. function init(){
  41. $interface=new ReflectionClass('Module');
  42. foreach($this->configData as $modulename=>$params){
  43. $module_class=new ReflectionClass($modulename);//根據配置configData的名稱,執行個體化ReflectionClass
  44. if(!$module_class->isSubclassOf($interface)){//檢查反射得到了類是否是$interface的子類
  45. throw new Exception("unknown module type:$modulename");//不是Module子類則拋出異常
  46. }
  47. $module=$module_class->newInstance();//執行個體化一個FtpModule或者PersonModule對象
  48. foreach($module_class->getMethods() as $method){//獲得類中的方法
  49. $this->handleMethod($module,$method,$params);
  50. }
  51. array_push($this->modules,$module);//將執行個體化的module對象放入$modules數組中
  52. }
  53. }
  54. function handleMethod(Module $module,ReflectionMethod $method,$params){
  55. $name=$method->getName();//獲得方法名稱
  56. $args=$method->getParameters();//獲得方法中的參數
  57. if(count($args)!=1||substr($name,0,3)!="set"){//檢查方法必須是以set開頭,且只有一個參數
  58. return false;
  59. }
  60. $property=strtolower(substr($name,3));//講方法名去掉set三個字母,作為參數
  61. if(!isset($params[$property])){//如果$params數組不包含某個屬性,就返回false
  62. return false;
  63. }
  64. $arg_class=@$args[0]->getClass;//檢查setter方法的第一個參數(且唯一)的資料類型
  65. if(empty($arg_class)){
  66. $method->invoke($module,$params[$property]);
  67. }else{
  68. $method->invoke($module,$arg_class->newInstance($params[$property]));
  69. }
  70. }
  71. }
  72. $test=new ModuleRunner();
  73. $test->init();
  74. ?>
複製代碼

二,通過反射擷取類的資訊:

  1. /**
  2. * php反射擷取類的資訊
  3. * edit bbs.it-home.org
  4. */
  5. class ReflectionUtil{
  6. static function getClassSource(ReflectionClass $class){
  7. $path=$class->getFileName();
  8. $lines=@file($path);
  9. $from=$class->getStartLine();
  10. $to=$class->getEndLine();
  11. $len=$to-$from+1;
  12. return implode(array_slice($lines,$from-1,$len));
  13. }
  14. }
  15. $classname="Person";
  16. $path="../practice/{$classname}.php";
  17. if(!file_exists($path)){
  18. throw new Exception("No such file as {$path}");
  19. }
  20. require_once($path);
  21. if(!class_exists($classname)){
  22. throw new Exception("No such class as {$classname}");
  23. }
  24. print ReflectionUtil::getClassSource(new ReflectionClass('Person'));
  25. ?>
複製代碼

輸出結果:

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; } }
  • 聯繫我們

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