Skip to content

Instantly share code, notes, and snippets.

@xuecan
Created May 30, 2016 13:44
Show Gist options
  • Select an option

  • Save xuecan/41a3095880edc1a82fc5fc429487737f to your computer and use it in GitHub Desktop.

Select an option

Save xuecan/41a3095880edc1a82fc5fc429487737f to your computer and use it in GitHub Desktop.
PHP Singletons
<?php
/**
* @copyright Copyright (C) 2006-2016 Xue Can <[email protected]> and contributors.
*/
namespace Singleton;
/**
* Singleton Design Pattern
*
* THIS IS CONSIDERED TO BE AN ANTI-PATTERN!
* FOR BETTER TESTABILITY AND MAINTAINABILITY USE DEPENDENCY INJECTION!
*
* @author Xue Can <[email protected]>
*/
class Singleton
{
/**
* @var Singleton[] The reference to *Singleton* instances of any child class.
*/
private static $instances = [];
/**
* Returns the *Singleton* instance of this class.
*
* @return static The *Singleton* instance.
*/
public static function getInstance()
{
if (!isset(self::$instances[static::class])) {
self::$instances[static::class] = new static();
}
return self::$instances[static::class];
}
/**
* Protected constructor to prevent creating a new instance of the
* *Singleton* via the `new` operator from outside of this class.
*/
protected function __construct()
{
}
/**
* Private clone method to prevent cloning of the instance of the
* *Singleton* instance.
*
* @return void
*/
final private function __clone()
{
}
/**
* Private unserialize method to prevent unserializing of the *Singleton*
* instance.
*
* @return void
*/
final private function __wakeup()
{
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment