单例配置文件

时间:2011-07-13 20:53:07

标签: php

嘿伙计我有一个类和单例方法的问题: 我创建这个类的目的是在其他类中使用配置值:

<?
class Config {


    public $values=array();
    protected static $_instance = null;

    //Getters
    function __get($prop) {
        return $this->values[$key];
    }

    //Setters   
    function __set($key, $value) {
        $this->values[$key]=$value;
    }

    //Singleton
    public static function getInstance() {
        if (self::$_instance === null) {
            $c = __CLASS__;
            self::$_instance = new $c;           
        }
        return self::$_instance;
    }
}?>

我创建了一个带有我的连接值的实例:

$config=new Config();
$config->conex=array(
    'database' => 'lala',
    'user' => 'lala',
    'password' => 'lala',
    'server' => 'localhost'
);

但是当我在数据库类中调用singleton方法时,值会丢失:

$config = Config::getInstance();
print_r($config->conex);

为什么会出现问题?

1 个答案:

答案 0 :(得分:0)

class Config {

    protected  $file;
    protected  $config;
    private static $instance = NULL;

    function __construct() {
        $this->file = CONFIG."config".".php";
    }
    /**
     * Returns a singleton instance of the Config
     * @return Config instance
     * @access public
     */
    function getInstance() {
        static $instance = array();
        if(!$instance) {
            $instance[0] = new Config();
        }
        return $instance[0];
    }
    /**
     * 
     * Load a configuration files
     * @param string $file
     * <p>Path to file</p>
     * @access private
     */
    private function load_config_file($file) {
        if(file_exists($file)) {
            require($file);
            $this->config = $config;
        }
    }
    /**
     * 
     * Reads information stored in the Config instance
     * <p>Usage:</p>
     * <p>Config::read("key"); will return value from a key in the config array in the
     * config file</p>
     * @param string $key
     * <p>Key of the config array which is an associative array</p>
     * <p>$config[$key]</p>
     * @access public
     */
    public function read($key) {
        $_this = Config::getInstance();
        $_this->load_config_file($_this->file);
        $ref = $_this->config;
        if(isset($ref[$key])) {
            return $ref[$key];
        }
    }