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
|
<?php
declare
(strict_types=1);
//开启强类型模式
class
Person
{
public
$name
;
protected
$hobbies
= [];
private
$age
;
/**
* 构造器
* Person constructor.
* @param string $name
* @param array $hobbies
* @param int $age
*/
public
function
__construct(string
$name
,
array
$hobbies
, int
$age
)
{
$this
->name =
$name
;
$this
->hobbies =
$hobbies
;
$this
->age =
$age
;
}
/**
* 判断是否符合人类的喜好
* @param string $hobby
* @return bool
*/
public
function
checkHobby(string
$hobby
)
{
if
(in_array(
$hobby
,
$this
->hobbies)) {
echo
$this
->name .
' very like '
.
$hobby
. PHP_EOL;
}
else
{
echo
$this
->name .
' not like '
.
$hobby
. PHP_EOL;
}
}
}
//1.获取指定类的反射类对象(初始化新的 ReflectionClass 对象。 )
//public ReflectionClass::__construct ( mixed $argument )
$reflectionClass
=
new
ReflectionClass(
'Person'
);
//2.获取反射类对象的实例(即反射实例)
//public object ReflectionClass::newInstance ( mixed $args [, mixed $... ] )
$reflectionInstance
=
$reflectionClass
->newInstance(
'zhangsan'
, [
'吃饭'
,
'睡觉'
,
'打豆豆'
], 18);
// 创建类的新的实例。给出的参数将会传递到类的构造函数。
/**
* Person Object
* (
* [name] => zhangsan
* [hobbies:protected] => Array
* (
* [0] => 吃饭
* [1] => 睡觉
* [2] => 打豆豆
* )
* [age:Person:private] => 18
* )
*
*/
//public object ReflectionClass::newInstanceArgs ([ array $args ] )
//$reflectionInstance1 = $reflectionClass->newInstanceArgs(['zhangsan', ['吃饭', '睡觉', '打豆豆'], 18]);// 创建类的新的实例。给出的参数将会传递到类的构造函数。
//echo $reflectionInstance == $reflectionInstance1;
//3.获取成员方法的反射方法类 ReflectionMethod( 获取一个类方法的 ReflectionMethod。)
//public ReflectionMethod ReflectionClass::getMethod ( string $name )
$reflectionMethod
=
$reflectionClass
->getMethod(
'checkHobby'
);
//4.执行一个反射的方法。
//public mixed ReflectionMethod::invoke ( object $object [, mixed $parameter [, mixed $... ]] )
//参数解析:
//$object为反射类的实例对象,
//$parameter为要反射的类的成员方法参数
echo
$reflectionMethod
->invoke(
$reflectionInstance
,
'coding php'
);
echo
$reflectionMethod
->invoke(
$reflectionInstance
,
'吃饭'
);
echo
$reflectionMethod
->invokeArgs(
$reflectionInstance
, [
'coding Java'
]);
echo
$reflectionMethod
->invokeArgs(
$reflectionInstance
, [
'dream'
]);
//(new Person('lisi', ['run', 'footbool', 'climb mountains'], 25))->checkHobby('Python');
|
本文转自 hgditren 51CTO博客,原文链接:http://blog.51cto.com/phpme/2051659,如需转载请自行联系原作者