Singleton pattern in PHP
08 Aug 2012Why singleton? Idea is to limit number of instances of a desired class, you don't want to have 4 connections to your DB server or 3 instances of session. First one you can but you dont want to do since resources are usually very limited and second one can create bunch of problems in logic.
In the good old days (actually older versions of PHP), developers used global variables to achieve this but that instantiated whole bunch of new problems. So how to do this?
I decided to create a simple session singleton class (this code here is stripped down only to show singleton related logic, the whole class can be found here):
class SessionSingleton
{
protected static $instance;
protected function __construct()
{
}
public static function getInstance()
{
if (static::$instance === null) {
static::$instance = new static();
}
return static::$instance;
}
}
</pre>
Key singleton features:
1) Constructor is marked as protected so any instantiation would cause a fatal error: "PHP Fatal error: Call to protected SessionSingleton::__construct() from invalid context in .."
$obj = new SessionSingleton();
</p>
2) Method getInstance() is here to instantiate SessionSingleton class only on first call and return already instantiated object every other time. Here is proper way to get object:
$obj = SessionSingleton::getInstance();
</p>
3) Static instance property is a placeholder where single instance of SessionSingleton will be 'saved' for future reuse and it is marked protected so no outside code could for instance delete it.
I've created a short script where you can see how multiple calls to SessionSingleton::getInstance() behave. There you can see that changing property in one of them will influence other one since both variables use same object instance.