note 86323 added to language.oop5.patterns

From: Date: Mon, 13 Oct 2008 08:59:52 +0000
Subject: note 86323 added to language.oop5.patterns
Groups: php.notes 
Request: Send a blank email to php-notes+get-145308@lists.php.net to get a copy of this message
Till now writing singleton classes depends on making class constructor private or protected and that sounds good, but what if class constructor must be public (for example, a singleton class inherits from a non-singleton class which already has a public constructor). The way to do so is: <?php class nonSingleton { protected $_foo; public function __construct($foo) { $this -> _foo = $foo; } } class Singleton extends nonSingleton { /** * Single instance of the class * * @var Singleton */ protected static $_instance = NULL; /** * A flag to know if we are in getInstance method or not. * * @var bool */ protected static $_withinGetInstance = false; /** * Public singleton class constructor * * @param mixed $foo */ public function __construct($foo) { if (! self :: $_withinGetInstance) throw new Exception('You cannot make a new instance of this class by using constructor, use getInstance() instead...'); parent :: __construct($foo); /* Any other operations constructor should do... */ } /** * Regular getInstance method * * @param mixed $foo * @return Singleton */ public static function getInstance($foo) { self :: $_withinGetInstance = true; if (! self :: $_instance) self :: $_instance = new Singleton($foo); self :: $_withinGetInstance = false; return self :: $_instance; } } ?> ---- Server IP: 69.147.83.197 Probable Submitter: 66.198.41.11 (proxied: 216.6.1.33) ---- Manual Page -- http://www.php.net/manual/en/language.oop5.patterns.php Edit -- https://master.php.net/note/edit/86323 Del: integrated -- https://master.php.net/note/delete/86323/integrated Del: useless -- https://master.php.net/note/delete/86323/useless Del: bad code -- https://master.php.net/note/delete/86323/bad+code Del: spam -- https://master.php.net/note/delete/86323/spam Del: non-english -- https://master.php.net/note/delete/86323/non-english Del: in docs -- https://master.php.net/note/delete/86323/in+docs Del: other reasons-- https://master.php.net/note/delete/86323 Reject -- https://master.php.net/note/reject/86323 Search -- https://master.php.net/manage/user-notes.php

« previous php.notes (#145308) next »