Skip to content

PHP Design Pattern – Singleton pattern

Knowing about Design patters is very essential in software designing and development, here in this post i am gonna write about singleton pattern, basically it is commonly used most useful well know pattern, it allows(create) only one instance to the given class on your script so we can avoid creating multiple instances. With this pattern we can use same instance of the class over and over in the script(we can use same instance to all the methods). we use global static variable to store the instance of class in singleton pattern. The best Example for singleton pattern is Database Connection object. see the bellow example script for better understanding, still if you any questions you can ask me via comment box.

PHP Design Pattern – Singleton pattern Example

// singleton design patren example class
class Singleton
    // Hold an instance of the class
	private static $singleton;

    // private constructor to prevent creating a new instance of the Singleton via the `new` operator from outside of this class.
    private function __construct() {

   //Private clone method to prevent cloning of the instance of the  Singleton instance.
    private function __clone() {
   // returns Singleton The Singleton instance.
    public static function getInstance()
        if (!isset(self::$singleton)) {
            self::$singleton = new Singleton();
        // static instance
        return self::$singleton;

    // Private unserialize method to prevent unserializing of the Singletoninstance.
    private function __wakeup() {
0 0 votes
Article Rating
Notify of

Inline Feedbacks
View all comments