php-reflectionClass-test 测试php反射机制

php反射的使用场景:

  • 快速定位函数或类所在的位置
  • 比较方便地实现插件机制
  • 抽取代码中的注释文档
  • 得到某个类中所有的方法、属性、注释、方法参数等
  • 抽象工厂

直接上代码了,以后在写理论;

UML类图如下:
反射机制

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
error_reporting(E_ALL);

//反射类
class MyReflection {
//var $memberId=0;

public function __construct($arr=array()){
echo "初始化MyReflection\n\n";
//$memberInfo=$this->read();
}

//保存信息
public function save(){
//利用反射机制该类的属性赋值
//$this->get_class_name();
$class=new ReflectionClass(get_class($this));
$object=$class->newInstanceArgs();
$properties=$class->getProperties();
foreach($properties as $property) {
$name=$property->getName();
//$this代表当前对象
$object->$name=$this->$name;
echo $property->getName()."\n";
}
var_dump($object);
echo "调用REST接口\n\n";
}

//读取信息
public function read(){
$memberInfoFromAPI=array(
'id'=>1,'name'=>'gangzi',
'phone'=>'13312345678','addr'=>'this is a addr',
);
//$object = REST
//$this->$name = $object->$name;
return $memberInfoFromAPI;
}
}

//会员类
class Member extends MyReflection{
var $id;
var $name;
var $phone;
var $addr;
//var $gradeHandle;

public function __construct($phone=''){
echo "初始化Member\n\n";
parent::__construct($phone='');
}
}

//会员等级类
class MemberGrade extends MyReflection{
var $grade;
var $id;

public function __construct($id=0){
}
}

//会员管理类
class MemberManager{
public function __construct(){
echo "初始化MemberManager\n\n";
}
//添加
public function add($arr=array()){
echo "调用添加会员信息API\n\n";
}
//检查是否存在
public function check($phone=''){
return true;
//return false;
}
}
echo "<pre>";
//调用过程
$oMM=new MemberManager;
$phone='12345678901';
$memberInfo=array('id'=>2,'name'=>'gangzi','phone'=>$phone,'addr'=>'this is a addr',);
if(false==$oMM->check($phone)){
$oMM->add($memberInfo);
}else{
//更新信息
$oM=new Member();
$oM->name = "xiaoming";
$oM->save();
//var_dump($oM);
}