tags:

views:

413

answers:

3

I am trying to access a static variable within a class by using a variable class name. I'm aware that in order to access a function within the class, you use call_user_func():

class foo {
    function bar() { echo 'hi'; }
} 
$class = "foo";
all_user_func(array($class, 'bar'));  // prints hi

However, this does not work when trying to access a static variable within the class:

class foo {
    public static $bar = 'hi';
} 
$class = "foo";
call_user_func(array($class, 'bar')); // nothing
echo $foo::$bar; // invalid

How do I get at this variable? Is it even possible? I have a bad feeling this is only available in PHP 5.3 going forward and I'm running PHP 5.2.6.

Thanks.

+6  A: 

For calling static members you can use a code like this:

call_user_func("MyClass::my_static_method");
// or
call_user_func(array("MyClass", "my_static_method"));

Unfortunately the only way to get static members from an object seems to be get_class_vars:

$vars = get_class_vars("MyClass");
$vars['my_static_attribute'];
Armin Ronacher
+2  A: 

You can use reflection to do this. Create a ReflectionClass object given the classname, and then use the getStaticPropertyValue method to get the static variable value.

class Demo
{
    public static $foo = 42;
}

$class = new ReflectionClass('Demo');
$value=$class->getStaticPropertyValue('foo');
var_dump($value);
Paul Dixon
A: 

@Paul - I have noticed that getStaticPropertyValue($prop) does not appear to work if $prop is anything but "public static". It will bork if $prop is declared "private static" or "protected static" in the class. I'm not exactly sure why, though.

brianjcohen