OO and "Singleton" class

From: Date: Tue, 01 Sep 2009 21:16:03 +0000
Subject: OO and "Singleton" class
Groups: php.general 
Request: Send a blank email to php-general+get-297583@lists.php.net to get a copy of this message
I'm a little fuzzy on some of the PHP implementation details for some stuff. In PHP (5 <= phpversion() < 5.3), I'd like a configuration class which can only effectively be instantiated once. Will the following code do this? Any other suggestions or corrections? (Code is untested. Feel free to complain about syntax.) class config { private static $cfg; // Initializes the configuration from main config file function __construct() { if (!is_array(self::$cfg)) { if (defined('CFGFILE')) { include(CFGFILE); self::$cfg = $config; } else self::$cfg = array(); } } // Returns a config item or null if not found function item($index) { if (array_key_exists($index, self::$cfg)) return self::$cfg[$index]; else return null; } // Sets a config item, optionally overwriting. // Returns true on success, false on failure. function set($index, $value, $overwrite = true) { $write = false; if (array_key_exists($index, self::$cfg) and $overwrite) $write = true; elseif (!array_key_exists($index, self::$cfg)) $write = true; if ($write) { self::$cfg[$index] = $value; return true; } else return false; } }; Paul -- Paul M. Foster

« previous php.general (#297583) next »