简体   繁体   English

扩展PHP中的单例类

[英]extends a singleton class in PHP

<?php
class LoveBase
{
    protected static $_instance = NULL;
    protected function __construct() {}
    public static function app()
    {
        if(self::$_instance == NULL) {
            self::$_instance = new self();
        }
        return self::$_instance;
    }

    public function get()
    {
        return 'LoveBase';
    }

}

class Love extends LoveBase
{
    public static function app()
    {
        if(self::$_instance == NULL) {
            self::$_instance = new self();
        }
        return self::$_instance;
    }
    public function get()
    {
        return 'Love';
    }
}

// Print "LoveLove" in this case(first case)
echo Love::app()->get(); 
echo LoveBase::app()->get();

// Print "LoveBaseLoveBase" in this case(second case)
// echo LoveBase::app()->get();
// echo Love::app()->get();
  1. Why the two different method come out the same result? 为什么两种不同的方法得出相同的结果?

  2. Compare the two case, the method will work when it's class instantiate first. 比较这两种情况,该方法在类首次实例化时将起作用。

(Sorry, I am not good at english, hopefully you can make sence) (对不起,我的英语不好,希望你能说出来)

You define two static functions, that both use the same static variable ($_instance) - a static member of the base class can also be access via subclasses (as long as it is not private). 您定义了两个静态函数,它们都使用相同的静态变量($ _instance)-基类的静态成员也可以通过子类访问(只要它不是私有的)。 Remember that static stuff (methods and variables) gets inherited, but not cloned. 请记住,静态的东西(方法和变量)是继承的,而不是克隆的。

Solution: Make the member variable private, and create one per class. 解决方案:将成员变量设为私有,并为每个类创建一个。

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

class Love extends LoveBase
{
    private static $_instance = NULL;
    // ...
// 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();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM