Created
May 30, 2016 13:44
-
-
Save xuecan/41a3095880edc1a82fc5fc429487737f to your computer and use it in GitHub Desktop.
PHP Singletons
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| <?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