PHP7 Singleton

This commit is contained in:
Dominik Liebler
2016-09-22 13:07:59 +02:00
parent e675a5f0ac
commit 4cf817b143
2 changed files with 12 additions and 35 deletions

View File

@@ -2,22 +2,17 @@
namespace DesignPatterns\Creational\Singleton;
/**
* class Singleton.
*/
class Singleton
{
/**
* @var Singleton reference to singleton instance
* @var Singleton
*/
private static $instance;
/**
* gets the instance via lazy initialization (created on first usage).
*
* @return self
* gets the instance via lazy initialization (created on first usage)
*/
public static function getInstance()
public static function getInstance(): Singleton
{
if (null === static::$instance) {
static::$instance = new static();
@@ -27,33 +22,30 @@ class Singleton
}
/**
* is not allowed to call from outside: private!
* is not allowed to call from outside to prevent from creating multiple instances,
* to use the singleton, you have to obtain the instance from Singleton::getInstance() instead
*/
private function __construct()
{
}
/**
* prevent the instance from being cloned.
* prevent the instance from being cloned (which would create a second instance of it)
*
* @throws SingletonPatternViolationException
*
* @return void
*/
final public function __clone()
{
throw new SingletonPatternViolationException('This is a Singleton. Clone is forbidden');
throw new \Exception('This is a Singleton. __clone is forbidden');
}
/**
* prevent from being unserialized.
* prevent from being unserialized (which would create a second instance of it)
*
* @throws SingletonPatternViolationException
*
* @return void
*/
final public function __wakeup()
{
throw new SingletonPatternViolationException('This is a Singleton. __wakeup usage is forbidden');
throw new \Exception('This is a Singleton. __wakeup is forbidden');
}
}