15

I am trying to access a static method, but using a variable as the class name. Is this possible? I seem to be having issues with it. I want to be able to do something like this:

class foo {
    public static function bar() {
        echo 'test';
    }
}

$variable_class_name = 'foo';
$variable_class_name::bar();

And I want to be able to do similar using static variables as well.

dqhendricks
  • 19,030
  • 11
  • 50
  • 83

2 Answers2

21

That syntax is only supported in PHP 5.3 and later. Previous versions don't understand that syntax, hence your parse error (T_PAAMAYIM_NEKUDOTAYIM refers to the :: operator).

In previous versions you can try call_user_func(), passing it an array containing the class name and its method name:

$variable_class_name = 'foo';
call_user_func(array($variable_class_name, 'bar'));
BoltClock
  • 700,868
  • 160
  • 1,392
  • 1,356
  • looks great. Is there something similar for static properties? – dqhendricks Feb 20 '11 at 21:12
  • @dqhendricks: not sure about class variables. For arguments, use `call_user_func()` with variadic arguments (like `sprintf()`), or use `call_user_func_array()` with an array of arguments. Both of these functions return the return values of the methods. – BoltClock Feb 20 '11 at 21:14
  • 1
    @dqhendricks: see ["Getting static property from a class with dynamic class name in PHP"](http://stackoverflow.com/questions/1279081/getting-static-property-from-a-class-with-dynamic-class-name-in-php). – outis Apr 22 '11 at 05:03
8

You can use reflection for PHP 5.1 and above:

class foo {
    public static $bar = 'foobar';
}

$class = 'foo';
$reflector = new ReflectionClass($class);
echo $reflector->getStaticPropertyValue('bar');

> foobar
David Harkness
  • 35,992
  • 10
  • 112
  • 134