robinmitra
5/25/2015 - 2:52 AM

Singleton Pattern

Singleton Pattern

<?php

class Singleton
{
    protected static $instance = null;

    protected function __construct()
    {
    }

    public static function getInstance()
    {
        if (is_null(static::$instance)) {
            static::$instance = new static;
        }

        return static::$instance;
    }
}

class DbSingleton extends Singleton
{
    protected static $instance = null;
}

class FileSingleton extends Singleton
{
    protected static $instance = null;
}

$dbInstance = DbSingleton::getInstance();
$dbInstance->name = 'MySQL';

$fileInstance = FileSingleton::getInstance();
$fileInstance->name = 'File Sytem';

echo "DB Instance:\n";
var_export($dbInstance);

echo "\nFile Instance:\n";
var_export($fileInstance);
DB Instance: DbSingleton::__set_state(array( 'name' => 'MySQL', )) 

File Instance: FileSingleton::__set_state(array( 'name' => 'File Sytem', ))
<?php

class Singleton
{
    private static $instance = null;

    private function __construct()
    {
    }

    public static function getInstance()
    {
        if (is_null(self::$instance)) {
            self::$instance = new self;
        }

        return self::$instance;
    }

    public static function destroy()
    {
        self::$instance = null;
        echo "\nSingleton instance after destroy():\n";
        var_dump(self::$instance);
    }
}

$instance1 = Singleton::getInstance();
$instance1->name = 'Robin Mitra';

echo "Instance 1:\n";
var_dump($instance1);

$instance2 = Singleton::getInstance();
echo "\nInstance 2:\n";
var_dump($instance2);

$instance2->name = 'John Doe';
Singleton::destroy();

echo "\nInstance 1 after destroy():\n";
var_dump($instance1);
Instance 1:
object(Singleton)#1 (1) {
  ["name"]=>
  string(11) "Robin Mitra"
}

Instance 2:
object(Singleton)#1 (1) {
  ["name"]=>
  string(11) "Robin Mitra"
}

Singleton instance after destroy():
NULL

Instance 1 after destroy():
object(Singleton)#1 (1) {
  ["name"]=>
  string(8) "John Doe"
}
<?php

class Singleton
{
    /**
     * @var self Single instance
     */
    private static $instance = null;

    /**
     * Constructor is private, in order to disallow instantiation from outside.
     */
    private function __construct()
    {
    }

    /**
     * Return the single instance of the class.
     */
    public static function getInstance()
    {
        if (is_null(self::$instance)) {
            self::$instance = new self;
        }

        return self::$instannce;
    }
}