>我有一个带有私有构造函数的类,以防止直接实例化。
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();
在 PHP 5.4.5 中,我得到
PHP 致命错误:从上下文调用私有 MyClass::__construct() "扩展类"
但是在 PHP 5.1.6 中,一切都按预期工作
这是怎么回事?
另外:我没有写MyClass,我没有能力保护构造函数,如果我这样做可以解决问题,但我不能。
这是错误。你可以像这样修复你的代码(PHP> PHP5.3):
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 {
}