ID: 40968 Comment by: smlerman at gmail dot com Reported By: oriol dot gual at gmail dot com Status: Open Bug Type: Session related Operating System: Windows XP SP2 PHP Version: 5.2.1 New Comment:
The only thing that can guarantee only one instance of your class existing is that Singleton::$instance is the only place you store an instance and getInstance() is the only way to retrieve an instance. Once you create a second place that an instance can be stored, such as storing an instance somewhere else (in the session data) and destroying the instance in the static property (which happens when the script ends), you create a second way to retrieve an entirely different instance. In general, there's no 100% guaranteed way to ensure that only one instance of a given class can ever exist. Previous Comments: ------------------------------------------------------------------------ [2007-04-01 01:42:08] b dot fore at mail dot com That's a gross abuse of ext/session dude. ------------------------------------------------------------------------ [2007-03-31 16:54:52] oriol dot gual at gmail dot com Description: ------------ When storing an object of a singleton class in the session, you can have more than one instance of that class in other subsequent executions. Reproduce code: --------------- class Singleton { private static $instance; private function __construct() {} final public static function getInstance() { if (!isset(Singleton::$instance)) { Singleton::$instance = &new Singleton; } return Singleton::$instance; } } session_start(); if(!isset($_SESSION['singleton'])) $_SESSION['singleton'] = Singleton::getInstance(); $test = Singleton::getInstance(); $anotherTest = Singleton::getInstance(); var_dump(Singleton::getInstance() === $test); var_dump(Singleton::getInstance() === $anotherTest); var_dump($test === $anotherTest); var_dump(Singleton::getInstance() === $_SESSION['singleton']); var_dump($test === $_SESSION['singleton']); var_dump($anotherTest === $_SESSION['singleton']); session_write_close(); Expected result: ---------------- Session not started (first execution) bool(true) bool(true) bool(true) bool(true) bool(true) bool(true) Subsequent executions bool(true) bool(true) bool(true) bool(true) bool(true) bool(true) Actual result: -------------- Session not started (first execution it's OK) bool(true) bool(true) bool(true) bool(true) bool(true) bool(true) Subsequent executions (fails, multiple instances) bool(true) bool(true) bool(true) bool(false) bool(false) bool(false) ------------------------------------------------------------------------ -- Edit this bug report at http://bugs.php.net/?id=40968&edit=1