我有一個單例類用於初始化error_handling。單身 - 嘗試初始化創建時的靜態屬性失敗
這個類需要一個Zend_Config對象和可選的$ appMode參數,以允許在測試此類時覆蓋已定義的APPMODE常量。如果我使用非靜態屬性創建對象,但一切正常,但在調用通常的getInstance()時,初始化靜態屬性不像我所期望的那樣工作。
class ErrorHandling{
private static $instance;
private static $_appMode; // not initialised in returned instance
private $_errorConfig;
private function __construct(Zend_Config $config, $appMode = null){
$this->_errorConfig = $config;
if(isset($appMode)){
static::$_appMode = $appMode;
}else{
static::$_appMode = APPMODE;
}
}
private final function __clone(){}
public static function getInstance(Zend_config $config, $appMode = null){
if(! (static::$instance instanceof self)){
static::$instance = new static($config, $appMode);
}
return static::$instance;
}
}
不,我真的需要 $ _appMode是靜態的一切,我宣佈其私人和感動,但我還是想知道,如果人們可以從一個靜態函數調用初始化靜態屬性。如果我真的需要靜態$ _appMode,我可以創建對象,然後用setter方法設置值,但這並不是「感覺」是做這件事的最好方法。
由於某些原因,我無法在構造函數中爲單例設置靜態屬性。 – stefgosselin 2011-05-19 05:23:55
@stefgosselin,我編輯了我的答案。現在試試吧 – azat 2011-05-19 19:16:19
謝謝,我沒有試過self :: $ instance = new ErrorHandling($ config,$ appMode);我相信我使用self :: $ instance = new self($ config,$ appMode);在原始代碼中。也是使用靜態::返回值,顯然這個關鍵字只用於賦值。感謝您的反饋; o) – stefgosselin 2011-05-20 03:34:48