Cambiata
Cambiata

Reputation: 3845

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

Let's say I have this class:

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

How could I use reflection to get a list of the static fields? (Something like array('$FOO', '$BAR')?)

Upvotes: 1

Views: 721

Answers (1)

Francois Deschenes
Francois Deschenes

Reputation: 24969

You'll want to use [ReflectionClass][1]. The getProperties() function will return an array of ReflectionProperty objects. The ReflectionProperty object have a isStatic() method which will tell you whether the property is static or not and a getName() method that return the name.

Example:

<?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);

Upvotes: 1

Related Questions