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. 解析流中的Xml文件时,报错:java.net.MalformedURLException: no protocol

    原来的代码: // 创建DocumentBuilder对象 DocumentBuilder b = a.newDocumentBuilder(); // 通过DocumentBuilder对象的par ...

  2. Java基础:IO流之字节流和字符流

    1. 流的概念 流(stream)的概念源于UNIX中管道(pipe)的概念.在UNIX中,管道是一条不间断的字节流,用来实现程序或进程间的通信,或读写外围设备.外部文件等. 一个流,必有源端和目的端 ...

  3. RAC集群安装校验输出信息

    RAC集群安装校验输出信息 作者:Eric 微信:loveoracle11g [grid@rac-node1 grid]$ [grid@rac-node1 grid]$ ./runcluvfy.sh ...

  4. SAS 报表输出一些新式控制

    SAS 报表输出一些新式控制 *******************************:*Purpose: 报表*Programm: *Programmor: *Date: *Version: ...

  5. core 部署

    perfmoneventvwr 1.yum install mysql2.yum install libgdiplus-devel3.COMPlus_ThreadPool_ForceMinWorker ...

  6. JavaScript类继承, 用什么方法好

    JavaScript类继承, 用什么方法好 一个实例: 基类Car: function Car(color, year) { this.name = "car"; this.col ...

  7. tp3.2 支付宝app支付

    pay方法 /** *支付宝支付 */ public function pay($param) { vendor('alipay.AopSdk');// 加载类库 $config = array( ' ...

  8. scrapy中 selenium(中间件) + 语言处理 +mysql

    在通过scrapy框架进行某些网站数据爬取的时候,往往会碰到页面动态数据加载的情况发生,如果直接使用scrapy对其url发请求,是绝对获取不到那部分动态加载出来的数据值.但是通过观察我们会发现,通过 ...

  9. 如何通过权限控制EXP导出指定的表

    今天一客户朋友咨询一个Oracle数据库用户EXP权限控制的问题,问我有没有办法可以解决.问题是这样的: 目前他们那边有外面的开发公司人员在核心系统做开发,考虑到系统数据的敏感性,给他们建了一个数据库 ...

  10. 使用idea创建maven多模块项目

    前言 参看:http://blog.csdn.net/zht666/article/details/19040733 使用Maven管理项目时,往往需要创建多个模块,模块之间存在相互引用的关系.对于M ...