单一实例 - 尝试在创建时初始化静态属性失败


singleton - trying to initialise a static property on creation fails

我有一个单例类用于初始化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 方法设置值,但这并不"感觉"是执行此操作的最佳方法。

结帐

<?
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之间的区别 - 后期静态绑定

你可能不使用任何 5.3.x 版本的 PHP。"后期静态绑定"(static::$_appMode)以前在任何版本中都不可用。请改用self::$_appMode。它与static略有不同,但在您的情况下应该没问题。有关更多信息,请阅读手册:后期静态绑定