logo

PHP Singleton Design Pattern

Code example for Singleton in PHP

Category: PHP

by designzone

2015-05-02 21:18:22

Singleton class in PHP:
/**
 * Singleton class
 *
 */
final class Singleton {
    /**
     * grab the singleton
     *
     * @return Singleton
     */
    public static function getInstance() {
        static $inst = null;
        if ($inst === null) {
            $inst = new Singleton();
        }
        return $inst;
    }

    /**
     * Construct method made protected so nobody else can make a
     * "new Singleton" from outside
     */
    protected function __construct() {
        //do nothing
    }

    /**
     * Make clone method private so nobody can clone an instance
     */
    private function __clone() {
        //do nothing
    }

}

test.php to test out Singleton
include "Singleton.class.php";

$instance1 = Singleton::getInstance();
$instance2 = Singleton::getInstance();

//each is an instance of the same object
echo "<pre>\n";
var_dump($instance1);
echo "</pre><br>\n";
echo "<pre>\n";
var_dump($instance2);
echo "</pre>\n";

//this will fail
$instance3 = new Singleton();

comments powered by Disqus