Monday, September 1, 2008

Implement Singleton pattern with PHP 5


We always create multiple instances of a class when we do programming but sometimes it is necessary to restrict people to create more than one instance of a class and this is where singleton comes into play.


Singleton classes use a static function to return its instance so that no matter how many object created in the class it uses the same object reference i.e all the instances share the same reference (because of the behavior of static)

ex -

public static function getObject()
{
if(!isset(self::$instance))
{
$object= __CLASS__;
self::$instance=new $object;
}

return self::$instance;
}

we can call this method MyClass::getObject(); if the class name is MyClass

No comments: