2011-07-13 11 views
0

やあみんな、私はクラスで問題とシングルトンの方法があります:私は他の人、クラス内での使用の設定値の意思whithこのクラスを作る を:シングルトン設定ファイル

<? 
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; 
    } 
}?> 

私は私の値whithインスタンスを作りますたっ:私は、データベースクラス内シングルトンメソッドを呼び出したときしかし、値が失われ

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

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

なぜ問題がありますか?

+0

あなたはシングルトンを使うべきではありません – dynamic

答えて

0

クラスコンフィグ{

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]; 
     } 
    } 
関連する問題