singleton - trying to initialise a static property on creation fails

放肆的年华 提交于 2019-12-20 05:45:37

问题


I have a singleton class used to initialise error_handling.

The class as is takes a Zend_Config object and optional $appMode in parameter, to allow overriding the defined APPMODE constant when testing this class. All is fine if I create the object with non-static properties, but initialising a static property does not work the way I expected when calling the usual 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;
 }
}

Not that I really need $_appMode to be static at all, I declared it private and moved on, but I am still wondering if one can initialise static properties from a static function call. If I REALLY needed static $_appMode, I could probably create the object and set the value afterwards with a setter method but this doesn't "feel" as being the best way to do this.


回答1:


Checkout

<?

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());

Is that your want?

Your could read here about difference between static and self- late static binding




回答2:


You probably don't use any 5.3.x-Version of PHP. "Late Static Binding" (static::$_appMode) is not available in any version before. Use self::$_appMode instead. Its slightly different from static, but in your case it should be OK. For further info read Manual: Late Static Binding



来源:https://stackoverflow.com/questions/6039692/singleton-trying-to-initialise-a-static-property-on-creation-fails

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!