获取PHP类的所有属性和所有方法,可通过反射机制

混江龙づ霸主 提交于 2020-01-12 11:37:34
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
<?php
 
class Class1{
    public $var1 = 'var1';
    public $var2 = 'var2';
    private $var3 = 'var3';
 
    public function method1(){}
    public function method2(){}
    private function method3(){}
}
 
print_r(get_class_methods(Class1));
print_r(get_class_vars(Class1));
 
 
//用反射类可以获得私有属性和私有方法
$ref = new ReflectionClass(Class1);//Class1 可以为对象实例 $class = new Class();
 
print_r($ref->getMethods());
print_r($ref->getProperties());

输出

 

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
Array
(
    [0] => method1
    [1] => method2
)
Array
(
    [var1] => var1
    [var2] => var2
)
Array
(
    [0] => ReflectionMethod Object
        (
            [name] => method1
            [class] => Class1
        )
 
    [1] => ReflectionMethod Object
        (
            [name] => method2
            [class] => Class1
        )
 
    [2] => ReflectionMethod Object
        (
            [name] => method3
            [class] => Class1
        )
 
)
Array
(
    [0] => ReflectionProperty Object
        (
            [name] => var1
            [class] => Class1
        )
 
    [1] => ReflectionProperty Object
        (
            [name] => var2
            [class] => Class1
        )
 
    [2] => ReflectionProperty Object
        (
            [name] => var3
            [class] => Class1
        )
 
)
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!