2011-05-18 29 views
0

我有一個單例類用於初始化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方法設置值,但這並不是「感覺」是做這件事的最好方法。

回答

0

結帳

<? 

class ErrorHandling{ 

    private static $instance; 
    private static $_appMode; // not initialised in returned instance 
    private $_errorConfig; 

private function __construct(array $config, $appMode = null){ 

    $this->_errorConfig = $config; 

    if(isset($appMode)){ 
     self::$_appMode = $appMode; 
    }else{ 
     self::$_appMode = APPMODE; 
    } 
} 

private final function __clone(){} 

public static function getInstance(array $config, $appMode = null){ 
    if(! (self::$instance instanceof self)){ 
     self::$instance = new ErrorHandling($config, $appMode); 
    } 
    return self::$instance; 
} 

public static function getAppMode() { 
    return self::$_appMode; 
} 
} 

$e = ErrorHandling::getInstance(array('dev' => true), -255); 
var_dump($e, ErrorHandling::getAppMode()); 

那是你想要的嗎?

你能念之間這兒大約差異staticself - late static binding

+0

由於某些原因,我無法在構造函數中爲單例設置靜態屬性。 – stefgosselin 2011-05-19 05:23:55

+0

@stefgosselin,我編輯了我的答案。現在試試吧 – azat 2011-05-19 19:16:19

+0

謝謝,我沒有試過self :: $ instance = new ErrorHandling($ config,$ appMode);我相信我使用self :: $ instance = new self($ config,$ appMode);在原始代碼中。也是使用靜態::返回值,顯然這個關鍵字只用於賦值。感謝您的反饋; o) – stefgosselin 2011-05-20 03:34:48

0

你可能不使用PHP的任何5.3.x-版本。 「後期靜態綁定」(static::$_appMode)在之前的任何版本中都不可用。改爲使用self::$_appMode。它與static略有不同,但在你的情況下,它應該是確定的。有關更多信息,請參閱Manual: Late Static Binding