From 52ef48fd28ca40ed9e4e48dd05955c441280b279 Mon Sep 17 00:00:00 2001 From: Oleksandr Date: Sat, 21 Sep 2013 22:05:13 +0200 Subject: [PATCH] Update Singleton.php Hi! I'm sure current realization of singleton is classic variance of the pattern. But not really correct (more then is mistaken for me) in relation to real codding on PHP projects. ;) ```php class A extends Singleton // Singleton which used static inside of getInstance() method {} class B extends A {} $a = A::getInstance(); $b = B::getInstance(); $c = Singleton::getInstance(); $a === $b && $b === $c; // returned FALSE ``` when u would be utilized Singleton updated then expression above returned TRUE. --- Singleton/Singleton.php | 14 +++++++++----- 1 file changed, 9 insertions(+), 5 deletions(-) diff --git a/Singleton/Singleton.php b/Singleton/Singleton.php index ee896e4..c728c31 100644 --- a/Singleton/Singleton.php +++ b/Singleton/Singleton.php @@ -16,6 +16,11 @@ namespace DesignPatterns; */ class Singleton { + /** + * @var cached reference to singleton instance + */ + protected static $instance; + /** * gets the instance via lazy initialization (created on first usage) * @@ -23,13 +28,12 @@ class Singleton */ public static function getInstance() { - static $instance; - - if (null === $instance) { - $instance = new self(); + + if (null === static::$instance) { + static::$instance = new static; } - return $instance; + return static::$instance; } /**