龙空技术网

php反射使用技巧详解

IT生涯 814

前言:

而今姐妹们对“php 反射”大致比较关注,大家都想要分析一些“php 反射”的相关资讯。那么小编同时在网摘上收集了一些关于“php 反射””的相关知识,希望我们能喜欢,看官们快快来了解一下吧!

PHP 5 具有完整的反射 API,添加了对类、接口、函数、方法和扩展进行反向工程的能力。 此外,反射 API 提供了方法来取出函数、类和方法中的文档注释。

1.反射有什么作用

反射可以用作文档生成。 反射可以做hook插件功能或者动态代理

通过反射我们可以得到一个类的相关属性:

常量 Contants 属性 Property Names 方法 Method Names静态 属性 Static Properties 命名空间 Namespace Person类是否为final或者abstract

2.如何使用反射

2.1获得反射

如下有一个简单的Person类

<!--?php

class Person {

protected $name ;

protected $age;

public function getName() {

return $this--->name;

}

public static function getAge() {

return $this->age;

}

}

我们只需要把类名’Person’传给ReflectionClass即可得到Person的反射。

$class = new ReflectionClass('Person');

$instance = $class->newInstanceArgs();

2.2获取属性

$properties = $class->getProperties();

foreach( $properties as $pro ) {

echo $pro->getName()."\n";

}

输出如下:

2.3获取方法

$method = $class->getMethods();

var_dump($method);

输出如下:

2.4执行类的方法

$getName = $method[0];

$getName->invoke($instance);

//或者

$instance->getName();

上述就可以执行类中的方法。

标签: #php 反射