Home  >  Article  >  Backend Development  >  Application examples of reflection in php

Application examples of reflection in php

WBOY
WBOYOriginal
2016-07-25 08:58:31971browse
  1. /**
  2. * php reflection example
  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():$hostn";
  17. }
  18. function setUser($user){
  19. print "FtpModule::setUser():$usern";
  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 reflection to obtain class information
  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; } }


Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn