note 109952 deleted from language.oop5 by aharvey

From: Date: Wed, 05 Sep 2012 09:45:40 +0000
Subject: note 109952 deleted from language.oop5 by aharvey
References: 1  Groups: php.notes 
Request: Send a blank email to php-notes+get-190513@lists.php.net to get a copy of this message
Note Submitter: innadiated at zeh gmail ---- Here is my solution for a flexible singleton pattern: <?php /** * @note $_instance is the second (non-singleton) instance. */ class SingletonException extends Exception { private $_instance = null; public function __construct (Singleton &$instance) { parent::__construct(sprintf("Singleton instance of Object '%s' already exists.", get_class($instance))); $this->_instance = &$instance; } public final function &getInstance () { return $this->_instance; } } abstract class Singleton { private static $_instance = array(); protected function __construct () { $className = get_class($this); if (array_key_exists($className, self::$_instance) and (self::$_instance[$className] !== $this)) { throw new SingletonException(self::$_instance[$className]); } } public function __destruct () { $className = get_class($this); if (array_key_exists($className, self::$_instance) and (self::$_instance[$className] === $this)) { unset(self::$_instance[$className]); } } protected static function &getInstance (Singleton $instance) { $className = get_class($this); if (!array_key_exists($className, self::$_instance)) { self::$_instance[$className] = $instance; } return self::$_instance[$className]; } } class SingletonImpl extends Singleton { public final static function &getInstance () { try { $instance = new SingletonImpl(); $return = &parent::getInstance($instance); } catch (SingletonException $e) { $return = &$e->getInstance(); } return $return; } } $singletonImpl = &SingletonImpl::getInstance(); ?> Cheers.

« previous php.notes (#190513) next »