尝试使用扩展单线的对象,但我无法做到。 如何从扩展类调用方法?
如何用单身人士显示13个非12人?
class SingletonTest
{
protected static $_instance;
private function __construct(){}
private function __clone(){}
public static function getInstance() {
if (null === self::$_instance) {
self::$_instance = new self();
}
return self::$_instance;
}
public function test2(){
return 12;
}
}
class ExtendSingleton extends SingletonTest
{
public function test2() {
return 13;
}
}
$b = ExtendSingleton::getInstance();
echo $b->test2(); //12
答案 0 :(得分:1)
public static function getInstance()
{
static $instances = array();
$calledClass = get_called_class();
if (!isset($instances[$calledClass]))
{
$instances[$calledClass] = new $calledClass();
}
return $instances[$calledClass];
}
答案 1 :(得分:1)
如果使用静态绑定关键字“static”而不是“self”
,您将获得所需的内容class SingletonTest
{
protected static $_instance;
private function __construct(){}
private function __clone(){}
public static function getInstance() {
if (null === static::$_instance) {
static::$_instance = new static();
}
return static::$_instance;
}
public function test2(){
return 12;
}
}
class ExtendSingleton extends SingletonTest
{
public function test2() {
return 13;
}
}
$b = ExtendSingleton::getInstance();
echo $b->test2(); //13
$a = SingletonTest::getInstance();
echo $a->test2(); //13
exit;
但正如您在上面的示例中看到的那样,您将首先调用“getInstance”的类将在$ _instance字段中存储它的实例。
无法创建基本单线类并继承单线态行为。
答案 2 :(得分:0)
所以这对你有用:
(首先通常函数是公共的,所以如果你从另一个类延伸,你可以使用它们!你需要从ExtendSingleton
而不是SingletonTest
来自ExtendSingleton
exdend的对象 - > SingletonTest
而不是其他方式。)
<?php
class SingletonTest {
protected static $_instance;
public function __construct() {
}
public function __clone() {
}
public static function getInstance() {
if (null === self::$_instance) {
self::$_instance = new self();
}
return self::$_instance;
}
public function test2(){
return 12;
}
}
class ExtendSingleton extends SingletonTest {
public function test2() {
return 13;
}
}
$b = new ExtendSingleton();
echo $b->test2(); //13
?>
输出:
13
答案 3 :(得分:0)
我已经测试了bicccio的解决方案并且可以正常使用
class SingletonTest
{
protected static $_instances = [];
private function __construct(){}
private function __clone(){}
public static function getInstance()
{
$calledClass = get_called_class();
if (!isset(self::$_instances[$calledClass]))
{
self::$_instances[$calledClass] = new $calledClass();
}
return self::$_instances[$calledClass];
}
public function test2(){
return 12;
}
}
class ExtendSingleton extends SingletonTest
{
public function test2() {
return 13;
}
}
$b = ExtendSingleton::getInstance();
echo $b->test2(); //13
$a = SingletonTest::getInstance();
echo $a->test2(); //12
答案 4 :(得分:0)
你可以使用后期静态绑定在php中扩展单例类,整个过程在这个问题中得到了很好的讨论。