Skip to content

Instantly share code, notes, and snippets.

@FlorianWolters
Created September 7, 2012 08:33
Show Gist options
  • Save FlorianWolters/3664366 to your computer and use it in GitHub Desktop.
Save FlorianWolters/3664366 to your computer and use it in GitHub Desktop.
Demonstration of the Singleton design pattern in PHP.
<?php
namespace FlorianWolters\Example\Pattern\Design\Creational\Singleton;
/**
* Demonstration of the *Singleton* design pattern in PHP.
*
* This is the correct implementation of the *Singleton* creational design
* pattern in the PHP programming language.
*
* - Prevents cloning of an instance via the `__clone()` magic method.
* - Prevents unserializing of an instance via the `__wakeup()` magic method.
*
* @author Florian Wolters <[email protected]>
* @copyright 2011-2012 Florian Wolters
* @license http://gnu.org/licenses/lgpl.txt LGPL-3.0+
* @link http://gist.github.com/3664366
* @since Class available since Release 0.1.0
*/
final class Singleton
{
// Declaring the class as "final" is required since one subclass would lead
// to unexpected behaviour.
/**
* Returns the *Singleton* instance of this class.
*
* @return SingletonInterface The *Singleton* instance.
*/
public static function getInstance()
{
// The *Singleton* instance of this class.
static $instance = null;
if (null === $instance) {
$instance = new self;
}
return $instance;
}
// @codeCoverageIgnoreStart
/**
* Protected constructor to prevent creating a new instance of this class
* via the `new` operator.
*/
protected function __construct()
{
// The constructor could also be declared with the visibility "private".
}
/**
* Private clone method to prevent cloning of the instance of this class.
*
* @return void
*/
final private function __clone()
{
}
/**
* Private unserialize method to prevent unserializing of the instance of
* this class.
*
* @return void
*/
final private function __wakeup()
{
}
// @codeCoverageIgnoreEnd
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment