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.

4
  • 1
    This works fine for me on php 5.3.2. Commented Feb 20, 2011 at 21:04
  • using 5.2 i believe. get an error like "Parse error: syntax error, unexpected T_PAAMAYIM_NEKUDOTAYIM in /some/path/application/models/lev_base_model.php on line 35" Commented Feb 20, 2011 at 21:08
  • What version of PHP are you running? As far as I'm aware you've been able to do this in recent versions (5.2+, though not exactly sure from when this would be valid) Commented Feb 20, 2011 at 21:08
  • @Gordon seems to only be allowed in 5.3+ Commented Feb 20, 2011 at 21:10

2 Answers 2

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'));
Sign up to request clarification or add additional context in comments.

3 Comments

looks great. Is there something similar for static properties?
@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.
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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.