使用PHP的反射Reflection获取对象信息

摘要:
PHP5添加了一个新函数:Reflection。此函数使程序员能够对类、接口、函数、方法和扩展进行反向工程。通过PHP代码,您可以获取有关对象的所有信息并与之交互。假设有一个类Person:classPerson{/**对于演示,我们“resettingisprivate*/private$_allowDynamicAttributes=false;/**type=primary_autoindentation*/protected$id=0;/*type=varcharlength=255null*/protected$name;/*type=textnull*/protected$biography;publicfunctiongetId(){return$this-˃id;}publicfunctionsetId($v){$this-˃id=$v;}public functiongetName(){return$this-˃name;}publicfunctionsetName($v){$this-˃name=$v;}public functiongetBiography(){return$sthis-˃biography;}公共函数setBiography,我们可以获得关于Person类的以下信息:常量Contants属性PropertyNames方法MethodNames静态属性StaticProperties命名空间NamespacePerson类是final或abstract只需将类名“Person”传递给ReflectionClass:1$class=newReflectionClass;获取属性:$properties=$class-˃getProperties();foreach{echo$property-˃getName().“n”;}//输出://_ AllowDynamicAttributes//id//name//biography默认情况下,ReflectionClass将获取所有属性,包括私有属性和受保护属性。返回的是ReflectionMethod对象的数组。最后,通过ReflectionMethod调用类中的方法。

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= newReflectionClass('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获取对象信息》仅用于学习参考。如对内容有疑问,请及时联系本站处理。

上篇tkinter学习(4)frame、pack、canvas学习快速生成网络mp4视频缩略图技术下篇

宿迁高防,2C2G15M,22元/月;香港BGP,2C5G5M,25元/月 雨云优惠码:MjYwNzM=

随便看看

crontab命令加载和使用

crontab命令用于设置定期执行的指令。在Linux系统中,Linux任务调度的任务主要分为以下两类:1.系统周期性执行的任务,如备份系统数据和清理缓存。2.个人要执行的任务:用户要定期执行的任务,例如每10分钟检查邮件服务器是否有新消息。这些任务可以由每个用户设置,以检查是否首先安装了crontab[root@localhostgjw]#rpm qa|g...

转:(WIN)S04-CH01 PCIE XDMA开发环境搭建以及环路测试

XDMAIP使用部分教程分LINUX篇和WINDOWS篇两个部分。通过实战,面向应用,提供给大家XILINXFPGAPCIE应用解决方案。本教程以MK7160FA作为样机测试。这是一款高性价比的FPGA开发板。而M_AXI_LITE挂载的BRAM是需要进行BAR空间操作,所以地址设置为0x80000000...

winform窗体(六)——DataGridView控件及通过此控件中实现增删改查

“,”Delete Data“,btn)==DialogResult.Yes){}V.多条件查询。如果用户没有输入任何内容或文本框为空,则查询所有内容。//设置两个常量条件stringtj1=”1=1“;stringtj2=”1=1”;//根据用户的输入更改条件。//如果用户输入名称If(name!=”“){tj1=“Namelike@name“;}//如果...

狼人杀规则

自爆后,所有演讲立即暂停,进入夜间。自爆后的那晚,狼人可以指着那把刀。预言家只能验证某个玩家是否是狼人,除狼人是否是狼人之外的所有信息都无法验证。如果先知测试丘比特,法官不必担心丘比特是哪一个阵营,只会展示好人的手势。...

sqlserver2016安装

2008以前的版本在SQLserver配置管理其中设置。...

easyExcel自动合并单元格

importcom.alibaba.excel.write.handler.CellWriteHandler;importorg.apache.poi.ss.usermodel.Sheet;importorg.apache.poi.ss.util.CellRangeAddress;int[]mergeColumnIndex){this.mergeRowInd...