PHP 反射机制的简单使用

2018-08-15 03:26:42   php分享记录

 

PHP 反射机制的简单使用,强制暴露类内属性和方法

  1. <?php
  2. /**
  3. * Created by PhpStorm.
  4. * User: john shuxian
  5. * Date: 2018/8/15
  6. * Time: 9:56
  7. */
  8. error_reporting(E_ALL);
  9. class person
  10. {
  11. public $name;
  12. public $gender;
  13. public function say(){
  14. echo $this->name,"\tis",$this->gender,"\r\n";
  15. }
  16. public function __set($name, $value)
  17. {
  18. // TODO: Implement __set() methods
  19. $this->$name = $value;
  20. }
  21. public function __get($name)
  22. {
  23. // TODO: Implement __get() method.
  24. if(!isset($this->$name)){
  25. echo "未设置";
  26. $this->$name = "正在为你设置默认值";
  27. }else{
  28. return $this->$name;
  29. }
  30. }
  31. }
  32. $student = new person();
  33. $student->name = 'tom';
  34. $student->gender = 'male';
  35. $student->age = 24;
  36. $reflect = new ReflectionObject($student);
  37. $className = $reflect->getName();
  38. $methods = $propertise = array();
  39. //获取属性列表
  40. $props = $reflect->getProperties();
  41. foreach ($props as $v){
  42. $propertise[$v->getName()] = $v;
  43. }
  44. foreach ($reflect->getMethods() as $v){
  45. $methods[$v->getName()] = $v;
  46. }
  47. echo "class {$className} \n{\n";
  48. is_array($propertise) && ksort($propertise);
  49. foreach ($propertise as $k=> $v){
  50. echo "\t";
  51. echo $v->isPublic()?'public':"",$v->isPrivate()?'private':'',$v->isProtected()?'protected':'',$v->isStatic()?'static':'';
  52. echo "\t{$k}\n";
  53. }
  54. echo "\n";
  55. if(is_array($methods)) ksort($methods);
  56. foreach ($methods as $k=>$v){
  57. echo "\tfunction {$k}(){}\n";
  58. }
  59. echo "}\n";

输出结果:

  1. class person
  2. {
  3. public age
  4. public gender
  5. public name
  6. function __get(){}
  7. function __set(){}
  8. function say(){}
  9. }