PHP Design Pattern – Singleton

The most commonly used design pattern in any language is Singleton design pattern. It provides a global access point to different modules in an application.

Some application resources are exclusive in that there is one and only one of this type of resource. For example, the connection to a database through the database handle is exclusive. You want to share the database handle in an application because it’s an overhead to keep opening and closing connections, particularly during a single page fetch.

Here is a simple way to create Singleton design pattern in php5:


/* mysingleton.php

* Author Naveen

* Created on 11/08/2012


class MySingleton{

private static $instance;

private $message = “Hello”;

public static function getSingleton()
if (!isset(self::$instance)) {

$className = __CLASS__;
self::$instance = new $className;
return self::$instance;

public function printMessage(){

echo $message;




To, use it you have to simply call the class, like mentioned below:

$singletonInstance = MySingleton::getSingleton();

echo $singletonInstance->printMessage();