在php中使用不同于5.1到5.4版本的私有构造函数扩展类
我有一个带有私有构造函数的类,以防止直接实例化在php中使用不同于5.1到5.4版本的私有构造函数扩展类,php,class,oop,inheritance,extend,Php,Class,Oop,Inheritance,Extend,我有一个带有私有构造函数的类,以防止直接实例化 class MyClass { private static $instance; private function __construct() { } public static function getInstance() { if (isset(self::$instance)) { return self::$instance; } else {
class MyClass {
private static $instance;
private function __construct() {
}
public static function getInstance() {
if (isset(self::$instance)) {
return self::$instance;
} else {
$c = __CLASS__;
self::$instance = new $c;
return self::$instance;
}
}
}
我扩展它
class ExtendedClass Extends MyClass {
//cannot touch parent::$instance, since it's private, so must overwrite
private static $instance;
//calling parent::getInstance() would instantiate the parent,
//not the extension, so must overwrite that too
public static function getInstance() {
if (isset(self::$instance)) {
return self::$instance;
} else {
$c = __CLASS__;
self::$instance = new $c;
return self::$instance;
}
}
}
当我打电话时
$myInstance=ExtendedClass::getInstance();
在PHP5.4.5中,我得到
PHP致命错误:从上下文调用私有MyClass::_construct()
“扩展类”
但在PHP5.1.6中,一切都按预期进行
这里发生了什么
另外:我没有编写MyClass,我没有能力使构造函数受到保护,如果我这样做可以解决问题,但我不能。是的。您可以这样修复代码(PHP>PHP5.3):
你为什么不让你的父构造函数受保护而不是私有的呢?我不能!我没有真正编写MyClass,我没有能力修改它。找到bug文档的方法!杰出的谢谢静态分析器会抱怨此代码不安全地使用new Static()。要解决此问题,还应使用
final
标记私有构造函数,以便它不能被重写。
class MyClass {
private static $instance;
private function __construct() {
}
static function getInstance() {
if (isset(self::$instance)) {
return self::$instance;
} else {
self::$instance = new static();
return self::$instance;
}
}
}
class ExtendedClass Extends MyClass {
}