views:

22

answers:

2

Hi folks!

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?

A: 

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
Gordon
+1  A: 

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'));
Pascal MARTIN
*cough* Five *cough* minutes :)
Gordon
When I started writting my answer, yours was not as complete as it is now ^^ *(There was only the first portion of the answer, with the name of the class hard-coded) -- and we both edited a couple of times ^^ *
Pascal MARTIN
Actually, I learned the shoot-early-then-add-stuff trick from you. Noticed you do do this several times and found it very cunning :)
Gordon
I learnt that from others, too ^^ ;; I generally consider that a basic *(but quick)* answer can help, if the guy who asked searches a bit more by himself ;; and if he waits a bit more or doesn't understand the basic answer, there will be a better one a couple of minutes after ;;; and I sometimes do this for answer that have been accepted, too, just so the accepted answer is better, and can help people reading it later *(when coming via google, for example)*.
Pascal MARTIN
Well, many thanks to the both of you, anyway :) As to which answer I should tag as accepted, I'll have to flip a coin.
Johan Fredrik Varen
@Johan : you're welcome :-) *(and for the "flip a coin" part, I have to admit that I smiled ^^ )*
Pascal MARTIN
@Johan I am young and need the reputation ;) J/K, go flip the coin.
Gordon
One F5 later, I suppose I got the right side of the coin :-D
Pascal MARTIN
/me *starts sobbing* ;) I guess that's c'est la vie
Gordon