在PHP中扩展单例类

在PHP中扩展单例类,php,singleton,Php,Singleton,您定义了两个静态函数,它们都使用相同的静态变量($\u instance)——基类的静态成员也可以通过子类访问(只要它不是私有的)。请记住,静态内容(方法和变量)是继承的,而不是克隆的 解决方案:将成员变量设为私有,并为每个类创建一个 // Print "LoveLove" in this case(first case) //Set self::$_instance to Love object id echo Love::app()->get(); //Static proper

您定义了两个静态函数,它们都使用相同的静态变量($\u instance)——基类的静态成员也可以通过子类访问(只要它不是私有的)。请记住,静态内容(方法和变量)是继承的,而不是克隆的

解决方案:将成员变量设为私有,并为每个类创建一个

// Print "LoveLove" in this case(first case)

//Set self::$_instance to Love object id
echo Love::app()->get(); 

//Static property $_instance is now already set, so LoveBase::app() won't create new self(), it will just return created and saved Love object
echo LoveBase::app()->get();

// Print "LoveBaseLoveBase" in this case(second case)

// Here is the same case, but static property $_instance filled with new self() in LoveBase class
// echo LoveBase::app()->get();
// echo Love::app()->get();

您定义了两个静态函数,它们都使用相同的静态变量($\实例)-基类的静态成员也可以通过子类访问(只要它不是私有的)。请记住,静态内容(方法和变量)是继承的,而不是克隆的

解决方案:将成员变量设为私有,并为每个类创建一个

// Print "LoveLove" in this case(first case)

//Set self::$_instance to Love object id
echo Love::app()->get(); 

//Static property $_instance is now already set, so LoveBase::app() won't create new self(), it will just return created and saved Love object
echo LoveBase::app()->get();

// Print "LoveBaseLoveBase" in this case(second case)

// Here is the same case, but static property $_instance filled with new self() in LoveBase class
// echo LoveBase::app()->get();
// echo Love::app()->get();

你能试着澄清你的问题吗?对你来说奇怪的是,在什么情况下你期望什么…?单身汉只是“假地球人”。尽量避开它们。另外,我通常认为单身不再是单身。你能试着澄清你的问题吗?对你来说奇怪的是,在什么情况下你期望什么…?单身汉只是“假地球人”。尽量避开它们。此外,延长单身期通常会让我觉得它不再是“单身”。
class LoveBase
{
    private static $_instance = NULL;
    // ...

class Love extends LoveBase
{
    private static $_instance = NULL;
    // ...