note 109952 added to language.oop5

From: Date: Wed, 05 Sep 2012 06:55:46 +0000
Subject: note 109952 added to language.oop5
Groups: php.notes 
Request: Send a blank email to php-notes+get-190511@lists.php.net to get a copy of this message
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. ---- Server IP: 69.147.83.197 Probable Submitter: 208.99.146.227 ---- Manual Page -- http://www.php.net/manual/en/language.oop5.php Edit -- https://master.php.net/note/edit/109952 Del: integrated -- https://master.php.net/note/delete/109952/integrated Del: useless -- https://master.php.net/note/delete/109952/useless Del: bad code -- https://master.php.net/note/delete/109952/bad+code Del: spam -- https://master.php.net/note/delete/109952/spam Del: non-english -- https://master.php.net/note/delete/109952/non-english Del: in docs -- https://master.php.net/note/delete/109952/in+docs Del: other reasons-- https://master.php.net/note/delete/109952 Reject -- https://master.php.net/note/reject/109952 Search -- https://master.php.net/manage/user-notes.php

« previous php.notes (#190511) next »