If you had a factory class that creates new objects of some kind, and that factroy class is a singleton, like this:
class Database_Factory extends Base_Factory {
private static $factory;
private $objects = array();
public function __get($profile) {
// check for object and return it if it's created before
}
public static function getInstance(){
if (!self::$factory)
self::$factory = new self();
return self::$factory;
}
}
The same code repeats anytime where some object needs it’s own factory. So i decided to make this factory class abstract and implement only specific routines for each factory. But PHP does not allow to instantiate abstract class.
abstract class Base_Factory {
public static function getInstance(){
if (!self::$factory)
self::$factory = new self();
return self::$factory;
}
}
Fatal error: Cannot instantiate abstract class Base_Factory
What would you do?
In PHP methods,
selfalways refers to the class where the method is defined. Since version 5.3.0, PHP supports “late static binding”, where you can use thestatickeyword to access overridden static methods, as well as the functionget_called_class()to get the name of the derived class in static context.However, your design has a major flaw: The static property
$factorydefined inBase_Factoryis shared across all derived classes. Therefore, the first time a singleton is created and stored in this property, all other calls togetInstance()will return the same object, no matter what derived class is used.You could use a static dictionary mapping class names to singleton objects:
Oh, one more thing: The fact that you are looking for a possibility to re-use code for singleton objects could be a cue to the fact that you are over-using the singleton design pattern! Ask yourself if the classes you are planning to implement as singletons really are singletons and if there will be no use case where you might want to have multiple instances of the particular class.
Often it is much better to use just one singleton representing the current “application context” that provides accessors for objects that are singletons with respect to this context.