OO and "Singleton" class

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

 



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

-- 
PHP General Mailing List (http://www.php.net/)
To unsubscribe, visit: http://www.php.net/unsub.php


[Index of Archives]     [PHP Home]     [Apache Users]     [PHP on Windows]     [Kernel Newbies]     [PHP Install]     [PHP Classes]     [Pear]     [Postgresql]     [Postgresql PHP]     [PHP on Windows]     [PHP Database Programming]     [PHP SOAP]

  Powered by Linux