Php:如何通过反射列出静态字段/属性


Php: How to list static fields/properties through reflection?

假设我有这样一个类:

class Example {    
    public static $FOO = array('id'=>'foo', 'length'=>23, 'height'=>34.2);
    public static $BAR = array('id'=>'bar', 'length'=>22.5, 'height'=>96.223);
}

我如何使用反射来获得静态字段的列表?(类似array('$FOO', '$BAR')?)

您将需要使用[ReflectionClass][1]getProperties()函数将返回ReflectionProperty对象的数组。ReflectionProperty对象有一个isStatic()方法,它将告诉您属性是否是静态的,还有一个getName()方法返回名称。

例子:

<?php
class Example {    
    public static $FOO = array('id'=>'foo', 'length'=>23, 'height'=>34.2);
    public static $BAR = array('id'=>'bar', 'length'=>22.5, 'height'=>96.223);
}
$reflection = new ReflectionClass('Example'); 
$properties = $reflection->getProperties();
$static = array();
if ( ! empty($properties) )
  foreach ( $properties as $property )
    if ( $property->isStatic() )
      $static[] = $property->getName();
print_r($static);