Tag Archives: factory

Singleton pattern in PHP 5.3

With the introduction of PHP 5.3 some nice object oriented features are available. One of them is the function get_called_class. Below a short example when this function comes in handy.

When we have an abstract CacheDriver as shown below and we extend this with a MemcachedDriver. We only want one instance of this driver available so we apply the singleton pattern. But before PHP 5.3 it was very difficult to put the getInstance method in the base class. There is a solution to use the factory pattern (eg. CacheDriver::getInstance('Memcached')) but the following solution is more elegant and possible from PHP 5.3

Because get_called_class() yields the name of the class we are using (MemcachedDriver) we get directly an instance of the MemcachedDriver without duplicating the getInstance method or using the factory pattern.