Singleton Design Pattern

Sometimes you want to use a class in different places in your code but want to refer to the same instance. You could create lots of instances or pass a reference around to a single instance. It would be better to have a class that only allows a single instance of itself to exist. This is known as the singleton design pattern. Here is an example implementation in PHP 5:

class MySingleton
{
    public static function getInstance()
    {
        static $inst = null;
        if ($inst == null){
            $inst = new MySingleton();
        }
        return $inst;
    }

    private function __construct()
    {
        /* Constructor stuff goes here! */
    }
    
    private function __clone()
    // Prevent Instance being cloned
    {
        trigger_error("Cannot clone instance of Singleton pattern.", E_USER_ERROR);
    }
}

Now, rather than creating an instance in the usual way i.e.

$instance = new MySingleton()

you would instead call the getInstance function:

$instance = MySingleton::getInstance()

In this way $instance will always be the same instance – there will never be more than one!

Sources: StackOverflow.com: Creating the Singleton design pattern in PHP5
DeveloperTutorials.com – The Singleton Design Pattern for PHP

Advertisements

About Mr Chimp

I make music, draw pictures, browse the internet, programme, and make sweet, sweet cups of tea until the early hours.
This entry was posted in Uncategorized and tagged , , , . Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s