2011-07-03 47 views
1

比方說,我有這個類: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); 
} 

我怎麼能使用反射來獲取靜態字段列表? (像array('$ FOO','$ BAR')?)

回答

1

你會想要使用[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); 
+0

謝謝,弗朗索瓦! – Cambiata

+0

@Cambiata - 不客氣。 –