简体   繁体   中英

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 static 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM