PHP5 具备完整的反射API,添加对类、接口、函数、方法和扩展进行反向工程的能力。php
反射是什么?api
它是指在PHP运行状态中,扩展分析PHP程序,导出或提取出关于类、方法、属性、参数等的详细信息,包括注释。这种动态获取的信息以及动态调用对象的方法的功能称为反射API。反射是操纵面向对象范型中元模型的API,其功能十分强大,可帮助咱们构建复杂,可扩展的应用。数组
其用途如:自动加载插件,自动生成文档,甚至可用来扩充PHP语言。函数
PHP反射api由若干类组成,可帮助咱们用来访问程序的元数据或者同相关的注释交互。借助反射咱们能够获取诸如类实现了那些方法,建立一个类的实例(不一样于用new建立),调用一个方法(也不一样于常规调用),传递参数,动态调用类的静态方法。this
反射api是PHP内建的OOP技术扩展,包括一些类,异常和接口,综合使用他们可用来帮助咱们分析其它类,接口,方法,属性,方法和扩展。这些OOP扩展被称为反射。spa
日常咱们用的比较多的是 ReflectionClass类 和 ReflectionMethod类,例如:插件
<?php class Person { /** * For the sake of demonstration, we"re setting this private */ private $_allowDynamicAttributes = false; /** * type=primary_autoincrement */ protected $id = 0; /** * type=varchar length=255 null */ protected $name; /** * type=text null */ protected $biography; public function getId() { return $this->id; } public function setId($v) { $this->id = $v; } public function getName() { return $this->name; } public function setName($v) { $this->name = $v; } public function getBiography() { return $this->biography; } public function setBiography($v) { $this->biography = $v; } }
1、经过ReflectionClass,咱们能够获得Person类的如下信息:code
常量 Contants对象
属性 Property Names接口
方法 Method Names静态
属性 Static Properties
命名空间 Namespace
Person类是否为final或者abstract
Person类是否有某个方法
接下来反射它,只要把类名"Person"传递给ReflectionClass就能够了:
$class = new ReflectionClass('Person'); // 创建 Person这个类的反射类 $instance = $class->newInstanceArgs($args); // 至关于实例化Person 类
1)获取属性(Properties):
$properties = $class->getProperties(); foreach ($properties as $property) { echo $property->getName() . "\n"; } // 输出: // _allowDynamicAttributes // id // name // biography
默认状况下,ReflectionClass会获取到全部的属性,private 和 protected的也能够。若是只想获取到private属性,就要额外传个参数:
$private_properties = $class->getProperties(ReflectionProperty::IS_PRIVATE);
可用参数列表:
ReflectionProperty::IS_STATIC
ReflectionProperty::IS_PUBLIC
ReflectionProperty::IS_PROTECTED
ReflectionProperty::IS_PRIVATE
经过$property->getName()能够获得属性名。
2)获取注释:
经过getDocComment能够获得写给property的注释。
foreach ($properties as $property) { if ($property->isProtected()) { $docblock = $property->getDocComment(); preg_match('/ type\=([a-z_]*) /', $property->getDocComment(), $matches); echo $matches[1] . "\n"; } } // Output: // primary_autoincrement // varchar // text
3)获取类的方法
getMethods() 来获取到类的全部methods。
hasMethod(string) 是否存在某个方法
getMethod(string) 获取方法
4)执行类的方法:
$instance->getName(); // 执行Person 里的方法getName // 或者: $method = $class->getmethod('getName'); // 获取Person 类中的getName方法 $method->invoke($instance); // 执行getName 方法 // 或者: $method = $class->getmethod('setName'); // 获取Person 类中的setName方法 $method->invokeArgs($instance, array('snsgou.com'));
2、经过ReflectionMethod,咱们能够获得Person类的某个方法的信息:
是否“public”、“protected”、“private” 、“static”类型
方法的参数列表
方法的参数个数
反调用类的方法
// 执行detail方法 $method = new ReflectionMethod('Person', 'test'); if ($method->isPublic() && !$method->isStatic()) { echo 'Action is right'; } echo $method->getNumberOfParameters(); // 参数个数 echo $method->getParameters(); // 参数对象数组