PHP5添加了一项新的功能:Reflection。这个功能使得程序员可以reverse-engineer class, interface,function,method and extension。通过PHP代码,就可以得到某object的所有信息,并且可以和它交互。

假设有一个类Person:

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;
}
}
   

通过ReflectionClass,我们可以得到Person类的以下信息:

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

只要把类名"Person"传递给ReflectionClass就可以了:

1 $class = new ReflectionClass('Person');

获取属性(Properties):

$properties = $class->getProperties();
foreach($properties as $property) {
echo $property->getName()."n";
}
// 输出:
// _allowDynamicAttributes
// id
// name
// biography

默认情况下,ReflectionClass会获取到所有的属性,private 和 protected的也可以。如果只想获取到private属性,就要额外传个参数:

1 $private_properties = $class->getProperties(ReflectionProperty::IS_PRIVATE);

可用参数列表:

  • ReflectionProperty::IS_STATIC
  • ReflectionProperty::IS_PUBLIC
  • ReflectionProperty::IS_PROTECTED
  • ReflectionProperty::IS_PRIVATE

如果要同时获取public 和private 属性,就这样写:ReflectionProperty::IS_PUBLIC | ReflectionProperty::IS_PROTECTED

应该不会感觉陌生吧。

通过$property->getName()可以得到属性名,通过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
   

有点不可思议了吧。竟然连注释都可以取到。

获取方法(methods):通过getMethods() 来获取到类的所有methods。返回的是ReflectionMethod对象的数组。不再演示。

最后通过ReflectionMethod来调用类里面的method。

$data = array("id" => 1, "name" => "Chris", "biography" => "I am am a PHP developer");
foreach($data as $key => $value) {
if(!$class->hasProperty($key)) {
throw new Exception($key." is not a valid property");
} if(!$class->hasMethod("get".ucfirst($key))) {
throw new Exception($key." is missing a getter");
} if(!$class->hasMethod("set".ucfirst($key))) {
throw new Exception($key." is missing a setter");
} // Make a new object to interact with
$object = new Person(); // Get the getter method and invoke it with the value in our data array
$setter = $class->getMethod("set".ucfirst($key));
$ok = $setter->invoke($object, $value); // Get the setter method and invoke it
$setter = $class->getMethod("get".ucfirst($key));
$objValue = $setter->invoke($object); // Now compare
if($value == $objValue) {
echo "Getter or Setter has modified the data.n";
} else {
echo "Getter and Setter does not modify the data.n";
}
}
   

使用PHP的反射Reflection获取对象信息的更多相关文章

  1. mysql数据库连接池使用(三)数据库元数据信息反射数据库获取数据库信息

    1.1. mysql数据库连接池使用(三)数据库元数据信息反射数据库获取数据库信息 有时候我们想要获取到数据库的基本信息,当前程序连接的那个数据库,数据库的版本信息,数据库中有哪些表,表中都有什么字段 ...

  2. 【Python】[面性对象编程] 获取对象信息,实例属性和类属性

    获取对象信息1.使用isinstance()判断class类型2.dir() 返回一个对象的所有属性和方法3.如果试图获取不存在的对象会抛出异常[AttributeError]4.正确利用对象内置函数 ...

  3. python基础——获取对象信息

    python基础——获取对象信息 当我们拿到一个对象的引用时,如何知道这个对象是什么类型.有哪些方法呢? 使用type() 首先,我们来判断对象类型,使用type()函数: 基本类型都可以用type( ...

  4. python 获取对象信息

    当我们拿到一个对象的引用时,如何知道这个对象是什么类型.有哪些方法呢? 使用type() 首先,我们来判断对象类型,使用type()函数: 基本类型都可以用type()判断: >>> ...

  5. python获取对象信息

    获取对象信息 拿到一个变量,除了用 isinstance() 判断它是否是某种类型的实例外,还有没有别的方法获取到更多的信息呢? 例如,已有定义: class Person(object): def ...

  6. Python面向对象 -- 继承和多态、获取对象信息、实例属性和类属性

    继承和多态 继承的好处: 1,子类可以使用父类的全部功能 2,多态:当子类和父类都存在相同的方法时,子类的方法会覆盖父类的方法,即调用时会调用子类的方法.这就是继承的另一个好处:多态. 多态: 调用方 ...

  7. python类的继承和多态,获取对象信息

    继承 类的继承机制使得子类可以继承父类中定义的方法,拥有父类的财产,比如有一个Animal的类作为父类,它有一个eat方法: class Animal(object): def __init__(se ...

  8. python 面向对象编程、获取对象信息

    面向对象与面向过程 参考链接:https://www.liaoxuefeng.com/wiki/0014316089557264a6b348958f449949df42a6d3a2e542c000/0 ...

  9. Python3类和实例之获取对象信息

    当我们拿到一个对象的引用时,如何知道这个对象是什么类型,有哪些方法呢 使用type() 判断对象类型使用type()函数 基本类型都可以用type()判断 <class 'int'> &g ...

随机推荐

  1. C# 读写 ini 配置文件

    虽说 XML 文件越发流行,但精简的 ini 配置文件还是经常会用到,在此留个脚印. 当然,文中只是调用系统API,不会报错,如有必要,也可以直接以流形式读取 ini文件并解析. /// <su ...

  2. 标准C库函数

    标准库函数由15个头文件组成 1.math.h 1.1 绝对值函数 1.2 幂函数.开平方函数 1.3 指数函数.对数函数 1.5 三角函数 注意参数范围: 1.6 取整函数.取余函数 2.字符串处理 ...

  3. T-SQL 视图

    use StudentManager go --判断视图是否存在 if exists(select * from sysobjects where name='view_ScoreQuery') dr ...

  4. 00004 - CentOS 7下安装pptp服务端

    主要配置步骤 1. 安装前检查系统支持 a. 在安装之前查看系统是否支持PPTP modprobe ppp-compress-18 && echo success 应该输出:succe ...

  5. OpenCV-Python基本功能

    一.图像读取/保存 import cv2 img = cv2.imread("name.png") cv2.imwrite('save.jpg', img) #显示图像 cv2.i ...

  6. Delphi疑难问题整理!!!

    一.Dll调用时报错,例如: TGetResPrice = function(var AName: string; AFileName: string): TResourceRecArray; std ...

  7. C++连接mysql及遇到的相关问题

    最近接触了很多数据库的东西,本来是一直接触的是sql server,不过由于项目需要就开始对mysql进行了连接.下面就让我这个菜鸟浅谈下经验吧. 对于C++连接mysql,我不太喜欢多下载一个软件m ...

  8. Android:真机调试遇到的问题(INSTALL_FAILED_CANCELLED_BY_USER和INSTALL_FAILED_INSUFFICIENT_STORAGE)

    Android:真机调试遇到的问题(INSTALL_FAILED_CANCELLED_BY_USER和INSTALL_FAILED_INSUFFICIENT_STORAGE) 刚开始做Android开 ...

  9. win7禁用Adnimistrator账号登录

    开始 运行 输入 lusrmgr.msc 回车. 双击 用户,双击Administrator ,在 账户已禁用 前面打上勾即可.然后确定.

  10. Linux常用操作分享

    Java开发经常遇到的linux相关操作 1.常用的上传下载(Xshell5) 1).get 从远程服务器上下载一个文件存放到本地,如下: 先通过lcd切换到本地那个目录下,然后通过get file ...