gpt4 book ai didi

php - 如何在 PHP 中继承单例?

转载 作者:可可西里 更新时间:2023-11-01 13:15:17 24 4
gpt4 key购买 nike

我正在尝试对使用单例模式的类进行子类化,并使用子类填充实例。

我好像有点小麻烦。

class Singleton {

static private $instance;

static public function instance(){
if(is_null(self::$instance)){
self::$instance = new self();
}
return self::$instance;
}

private function __construct(){}

}

class MySingleton extends Singleton {

}

echo get_class(MySingleton::instance()); //=> Singleton

//=> I'm hoping to see MySingleton

最佳答案

您要找的是late static binding这是 PHP 5.3 的新特性。尝试用 new static() 替换 new self(),这应该对你有用。

self 始终引用包含类,而 static 引用“被调用”类。

关于php - 如何在 PHP 中继承单例?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7987313/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com