mirror of
https://github.com/DesignPatternsPHP/DesignPatternsPHP.git
synced 2025-10-01 16:58:42 +02:00
PHP7 Singleton
This commit is contained in:
@@ -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');
|
||||
}
|
||||
}
|
||||
|
Reference in New Issue
Block a user