note 49699 deleted from language.variables.scope by danbrown

From: Date: Mon, 18 May 2009 01:39:48 +0000
Subject: note 49699 deleted from language.variables.scope by danbrown
References: 1  Groups: php.notes 
Request: Send a blank email to php-notes+get-155572@lists.php.net to get a copy of this message
Note Submitter: S dot Radovanovic at trimm dot nl ---- To use the Singleton Pattern (as available in PHP5), we must do a little trick in PHP4. Most examples I've seen look like this: //Creation of singleton, Example, Example1 objects //and then <? $myExample =& singleton('Example'); $myExample1 =& singleton('Example1'); ?> What I wanted was a way to use the Singleton Pattern on initialization of a new object (no calling of a method by reference (or something like that)). The initializor doesn't have to know that the object it is trying to initialize uses the Singleton Pattern. Therefor I came up with the following: Beneath is part of a Config object that allows me to retrieve configuration data read from specific ini files (through parse_ini_file). Because I wanted to use the Config object in different other objects without having to pass a reference to the Config object all the time and without some of them having to now how the Config object was loaded (which configuration file was used) I had the need for the Singleton pattern. To accomplish the Singleton pattern in the Constructor I've created a static array containing references to configuration file specific objects (each new configuration file creates a new instance of the Config object). If we then try to create a new instance of an already loaded Config object (with the same configuration file), the objects set this to the reference of the previously created object, thus pointing both instances to the same object. Here's the main part of the script. Here's an example of how to use the Config object: <?php //dataheader Config::setIniPath("/home/mydir/data/conffiles"); //object screen $objTemplateConfig = new Config("template.conf"); $objErrorConfig = new Config("error.conf"); //objTemplateConfig and objErrorConfig are 2 different instances $templatePath = $objTemplateConfig->get("template_path"); $errorColor = $objErrorConfig->get("error_color"); //object factory //If no file is stated, the last one is used, this way this instance will have the reference to the previously created instance of objErrorConfig in object screen $objErrorConfig = new Config(); $errorMessage = $objErrorConfig->get($errorName); ?> So without the initializor knowing it he/she has retrieved a reference to a previously instantiated Config object (knowledge of this resides with the object). Here's the constructor part of the config object:

« previous php.notes (#155572) next »