反射:直观理解就是根据到达地找到出发地和来源。比如,一个光秃秃的对象,我们可以仅仅通过这个对象就能知道它所属的类、拥有哪些方法。
手册: 官网介绍
PHP 5 具有完整的反射 API,添加了对类、接口、函数、方法和扩展进行反向工程的能力。 此外,反射 API 提供了方法来取出函数、类和方法中的文档注释。
请注意部分内部 API 丢失了反射扩展工作所需的代码。 例如,一个内置的 PHP 类可能丢失了反射属性的数据。这些少数的情况被认为是错误,不过, 正因为如此,它们应该被发现和修复。
demo:通过ReflectionClass 类 ->反射 tets
类 ,得到中的属性和方法等
<?php
/**
* test测试类
*/
class test
{
/**
* $test 属性
*/
private $test = "";
public static $color='Red';
public function setTest($test)
{
$this->test = $test;
return $this;
}
/**
* getTest 方法
*/
public function getTest()
{
return $this->test;
}
}
反射类
$class = new ReflectionClass(new test()); ## 反射test 类
class ReflectionClass#1 (1) {
public $name =>
string(4) "test"
}
获取类的方法名
$methods = $class -> getMethods (); ## 获取方法的数组
array(2) {
[0] =>
class ReflectionMethod#2 (2) {
public $name =>
string(7) "setTest"
public $class =>
string(4) "test"
}
[1] =>
class ReflectionMethod#3 (2) {
public $name =>
string(7) "getTest"
public $class =>
string(4) "test"
}
}
注释
$doc=$class->getDocComment(); // 获取test类的注释文档,即定义在类之前的注释
string(26) "/**
* test测试类
*/"
$methoddoc = $class->getMethod('getTest')->getDocComment(); // 获取tets类中setPassowrd方法的注释
string(35) "/**
* getTest 方法
*/"
获取静态(static)属性 及属于值
$static=$class->getStaticProperties(); 获取静态(static)属性
array (size=1)
'color' => string 'Red' (length=3)
$vaule=$class->getStaticPropertyValue('color'); 获取静态(static)属性的值
string 'Red' (length=3)