PHP Development Web Development

PHP Singleton Pattern

Singleton pattern is used where you need to handle some kind of expensive task – like connection to a database – and you want to be sure that only one instance of an object exists at a time.

A very good example of such patter is below:

// Example of Singleton Class.
class DBConnection {
    // The class instance holder
    private static $instance = null;

    // Private constructor (!)
    // Impossible to create an object in a "normal" way
    private function __construct()
        // details/task of database connection

    // We use this static method to create an object
    // if the class has no instance yet.
    public static function getDBInstance()
        if (self::$instance == null) //check if already exists
            //doesn't exist, so create one
            self::$instance = new DBConnection();

        return self::$instance; //returned existing one

The main difference of a Singleton Pattern / Class is the fact, that constructor is private. It means, you cannot create an object from external world/code in a “normal” way so to speak. Instead, you can create object – if not yet created – using static method (in our example it is getDBInstance() );

So, we could create singleton this way:

$mysqlDBconnection = DBConnection::getDBInstance();

For more details read, in my opinion, the best article about Singleton Pattern here.