开发者

How do I reference a static method of a variable class in PHP?

I'm writing a factory class that should be able to return singleton instances of a number of different types, depending on the given parameter. The method would look something like this, but the way I'm referencing the singleton's sta开发者_开发知识库tic method is obviously wrong:

public function getService($singletonClassName) {
    return $singletonClassName::getInstance();
}

What would the correct syntax for such a reference look like in PHP?


You cannot use that kind of syntax with PHP < 5.3 : it's one of the new features of PHP 5.3

A couple of possibilities, with PHP 5.2, would be to :

  • use the name of the class, if you know it
  • Or use something like call_user_func


In the first case, it would be as simple as :

ClassName::getInstance()

And, in the second, you'd use something like :

call_user_func($singletonClassName .'::getInstance');

According to the documentation of call_user_func, this should work with PHP >= 5.2.3

Or you could just use :

call_user_func(array($singletonClassName, 'getInstance'));


You just use the class name

public function getService($singletonClassName) {
    return SingletonClassName::getInstance();
}

Alternatively, if $singleClassName is a variable containing the classname use

public function getService($singletonClassName) {
    return call_user_func( array($singletonClassName, 'getInstance') );
}

As of 5.2.3 you can also do

call_user_func($singletonClassName .'::getInstance'); // As of 5.2.3
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜