今天开始学习php 的反射,许多人可能还没有听说过反射这个概念,简单点说反射的就是让你拥有剖析类、函数的能力。
有的同学可能会问我剖析类有什么用,我为什么要学反射,我只能说不学反射并不会对你实现业务有任何影响,但是如果你想写出结构优雅的程序,想写出维护性和扩展性都很高的程序,学习反射是必不可少的。
PHP 内置了一组反射类来实现类的反射,常用的有:
- ReflectionClass 解析类
- ReflectionProperty 类的属性的相关信息
- ReflectionMethod 类方法的有关信息
- ReflectionParameter 取回了函数或方法参数的相关信息
想看全的就翻手册去。
今天先通过一段演示代码简单看下php的反射到底是个什么东西。
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
|
<?php
class Hero {
protected $name ;
protected $skills = [];
public function __construct( $name , $skills = []) {
$this ->name = $name ;
$this ->skills = $skills ;
}
public function attack( $hero ) {
echo "Attack {$hero->name}" . PHP_EOL;
}
public function execute( $index ) {
echo "Axecute {$index} skill" . PHP_EOL;
}
}
$ref = new ReflectionClass( 'Hero' );
if ( $ref ->isInstantiable()) {
echo '可以实例化' . PHP_EOL;
}
// 获取类的构造函数
$constructor = $ref ->getConstructor();
print_r( $constructor ); //ReflectionMethod E对象
//获取属性
if ( $ref ->hasProperty( 'name' )) {
$attr = $ref ->getProperty( 'name' );
print_r( $attr ); //ReflectionProperty 对象
}
// 获取属性列表
$attributes = $ref ->getProperties();
foreach ( $attributes as $row ) {
//row 为 ReflectionProperty 的实例
echo $row ->getName() . "\n" ;
}
// 获取方法
if ( $ref ->hasMethod( 'attack' )) {
$method = $ref ->getMethod( 'attack' );
//$method 为 ReflectionMethod 的实例
print_r( $method );
}
// 获取方法列表
$methods = $ref ->getMethods();
foreach ( $methods as $row ) {
//这的row 是 ReflectionMethod 的实例
echo $row ->getName() . PHP_EOL;
}
|
运行结果:
可以实例化
ReflectionMethod Object
(
[name] => __construct
[class] => Hero
)
ReflectionProperty Object
(
[name] => name
[class] => Hero
)
name
skills
ReflectionMethod Object
(
[name] => attack
[class] => Hero
)
__construct
attack
execute
学习新东西,首先是要有熟悉感,或者叫手感,有了手感你才会对它不畏惧,先把上面的代码抄上一篇,运行一下,你应该会对php 反射有一点初步的印象。
下一篇再做一个小例子,看看用发可以做什么神奇的事情。
希望本文所述对大家PHP程序设计有所帮助。
原文链接:https://blog.csdn.net/ltx06/article/details/78933170