Реализовать синглтон PHP: свойства статического класса или переменные статического метода? ⇐ Php
Реализовать синглтон PHP: свойства статического класса или переменные статического метода?
So, I've always implemented a singleton like so:
class Singleton { private static $_instance = null; public static function getInstance() { if (self::$_instance === null) self::$_instance = new Singleton(); return self::$_instance; } private function __construct() { } } However, it recently struck me that I could also implement it with member-wise static variables:
class Singleton { public static function getInstance() { //oops - can't assign expression here! static $instance = null; // = new Singleton(); if ($instance === null) $instance = new Singleton(); return $instance; } private function __construct() { } } To me, this is cleaner because it doesn't clutter the class, and I don't have to do any explicit existence check, but because I've never seen this implementation anywhere else, I'm wondering:
Is there anything wrong with using the second implementation over the first?
Источник: https://stackoverflow.com/questions/323 ... -variables
So, I've always implemented a singleton like so:
class Singleton { private static $_instance = null; public static function getInstance() { if (self::$_instance === null) self::$_instance = new Singleton(); return self::$_instance; } private function __construct() { } } However, it recently struck me that I could also implement it with member-wise static variables:
class Singleton { public static function getInstance() { //oops - can't assign expression here! static $instance = null; // = new Singleton(); if ($instance === null) $instance = new Singleton(); return $instance; } private function __construct() { } } To me, this is cleaner because it doesn't clutter the class, and I don't have to do any explicit existence check, but because I've never seen this implementation anywhere else, I'm wondering:
Is there anything wrong with using the second implementation over the first?
Источник: https://stackoverflow.com/questions/323 ... -variables
-
- Похожие темы
- Ответы
- Просмотры
- Последнее сообщение