问题描述
我有一个用于初始化error_handling的单例类。
I have a singleton class used to initialise error_handling.
类在参数中使用Zend_Config对象和可选的$ appMode,以允许覆盖定义的APPMODE常量当测试这个类。如果我创建具有非静态属性的对象,则一切正常,但初始化静态属性在调用通常的getInstance()时不会按预期的方式工作。
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;
}
}
不是我真的需要 $ _appMode根本就是静态的,我将其声明为私有并移动,但我仍然想知道是否可以从静态函数调用初始化静态属性。如果我真的需要静态$ _appMode,我可能会创建一个对象,然后使用setter方法设置该值,但这并不感觉为最好的方式。
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.
推荐答案
结帐
<?
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());
这是你想要的吗?
你的可以在这里阅读关于 static
和 self之间的差异
-
Your could read here about difference between static
and self
- late static binding
这篇关于单例 - 尝试初始化创建时的静态属性失败的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!