20

With a class like

class MyClass {
    static var1 = "a";
    static var2 = "b";
}

... I'd like to retrieve the static members and their values at runtime; something like

Array(
    "var1" => "a",
    "var2" => "b"
)

Is there any way to do this in PHP?

Phillip
  • 5,366
  • 10
  • 43
  • 62
  • 1
    I found get_class_vars(get_class($obj)), but that only works if $obj is an _instantiated_ object, not the class itself. If I'll only have static members in my class, I'd like to keep from having to instantiate the class. – Phillip Jan 06 '12 at 20:26
  • 1
    @Philip: You can edit your question and add the information you've placed in form of a comment much more nicely inside your question ;) – hakre Jan 06 '12 at 20:30
  • Related: [From the string name of a class, can I get a static variable?](http://stackoverflow.com/questions/3354628/from-the-string-name-of-a-class-can-i-get-a-static-variable) – hakre Jan 06 '12 at 20:35

2 Answers2

42

You can use ReflectionClass::getStaticProperties() to do this:

$class = new ReflectionClass('MyClass');
$arr = $class->getStaticProperties();
Array
(
    [var1] => a
    [var2] => b
)
1

http://www.php.net/manual/en/reflectionclass.getstaticproperties.php - try this

getting information about classes and class properties such as all static methods is called "reflection".

tehdoommarine
  • 1,868
  • 3
  • 18
  • 31
  • 1
    [link only answer](https://meta.stackexchange.com/a/8259). Please improve if possible. – T30 Oct 24 '17 at 11:14