PHP singleton design pattern, the easy way.

May 27th 2013

Using a singleton in PHP is the best way to pass an object throughout your application without having to set the values all over again.

A singleton allows you to declare an instance and then call that instance from anywhere in your code base.

Here's my base class for a singleton. Using it is easy, and by using a base class I can simple extend it for future new singleton classes.

PHP Code:
<?php
class Singleton
{
    
/**
     * @var Singleton
     */
    
protected static $_instance null;

    protected function 
__construct()
    {
    }

    
/**
     * Retrieve an instance of the given class.
     *
     * @return Singleton
     */
    
public static function getInstance()
    {
        if (!isset(static::
$_instance)) {
            static::
$_instance = new static;
        }
        return static::
$_instance;
    }

    protected function 
__clone()
    {
    }
}

You can use it like this:

PHP Code:
<?php
Singleton
::getInstance();

Obviously you'll need to create a new class for a specific purpose, such as a database connection resource, or shopping cart data.

But by using the Singleton base class you'll only need to write your setters and getters.