Skip to content

Instantly share code, notes, and snippets.

@robinmitra
Last active August 29, 2015 14:21
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save robinmitra/063828245708264b74f6 to your computer and use it in GitHub Desktop.
Save robinmitra/063828245708264b74f6 to your computer and use it in GitHub Desktop.
Singleton Pattern
<?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;
}
}
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
{
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);
DB Instance: DbSingleton::__set_state(array( 'name' => 'MySQL', ))
File Instance: FileSingleton::__set_state(array( 'name' => 'File Sytem', ))
<?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);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment