reading static class variables dynamically

liunx

Guest
Hello Group,

as I know, I can dynamically call functions of dynamic classes, like:

$myClassname = "MyClass";
$myMethodname = "myMethod";
$result = $myClassname->$myMethodname();

But what can I do, when I want to access a static class variable? A construction like
$myVariable = "MyStaticClass::${$myVariable}"
or even
$myMethodCall = "MyStaticClass::getStaticVariable"
does not work since the last only works if the method is defined directly in the mentioned class, not in a superclass. Does anybody know how to make it work correctly?

thx
Sebastianwell there are a few ways to go about.

To make things easy, all examples will use this class:
class MyStaticClass {
public static $foo = 'bar value';
}

1. If you know the name of the class, it is very easy:
$myVariable = 'foo';

if (property_exists('MyStaticClass', $myVariable)) {
echo MyStaticClass::$$myVariable;
}


If you don't know the name of the class at the time of coding, there are still ways to do this.

2. use get_class_vars()
$myClass = 'MyStaticClass';
$myVariable = 'foo';

if (property_exists($myClass, $myVariable)) {
$properties = get_class_vars($myClass);
echo $properties[$myVariable];
}

3. Use Reflection:
$myClass = 'MyStaticClass';
$myVariable = 'foo';

$reflector = new ReflectionClass($myClass);
echo $reflector->getStaticPropertyValue($myVariable, 'default value');
note, the ReflectionClass::getStaticPropertyValue() is PHP 5.1.0 or newer. on 5.0, you can use ReflectionClass::getStaticProperties() to get an array similar to get_class_vars().

4. use eval() (eval() has its purposes, but since there are at least 2 other ways to do this, you might consider avoiding eval() here):
$myClass = 'MyStaticClass';
$myVariable = 'foo';

if (property_exists($myClass, $myVariable)) {
echo eval("echo $myClass::\$$myVariable;");
}



Also note, property_exists() is only 5.1 or newer, and is not entirely necessary if you are sure that $myVariable exists as a property of the class. However if you try to call a static property that does not exist, it results in a fatal error (in 5.1.2 anyways), so it is probably best practice to use it in these situations.

And as a final note, no doubt there are also other methods to accomplish this (for example there are other ways to approach it using Reflection, different from the Reflection example I did). These are just methods that immediately came to mind.
 
Back
Top