2009-09-13 22 views
2

class ConfigReader { private static $ instance = NULL; protected $ configData = array();PHP和單例再次

public function getInstance() 
    { 
     if(self::$instance == NULL) 
     { 
      self::$instance == new ConfigReader(); 
     } 
     return self::$instance; 
    } 

    public function getConfigValue($getName) 
    { 
     echo 'In function'; 
    } 

    private function __construct() 
    { 
     $this->configData = %READ_FROM_DATABASE%; 
    } 

    private function __clone() {} 
} 

併爲:

var_dump(ConfigReader::getInstance()) 

我:NULL

我打破了腦筋......請幫助我。

回答

5

在getInstance方法,你應該只用一個 '=':你想的分配,而不是compatison:

self::$instance = new ConfigReader(); 

而不是

self::$instance == new ConfigReader(); 


這方法應聲明爲static,因爲您將其用作靜態方法:

public static function getInstance() 
{ 
    if(self::$instance == NULL) 
    { 
     self::$instance = new ConfigReader(); 
    } 
    return self::$instance; 
} 

考慮到這兩個修改,它應該工作;-)

6

僅有一個錯字:self::$instance == new ConfigReader()包含==代替=

5

的方法的getInstance()也應是靜態的。