在PHP中扩展单例类

时间:2012-06-25 17:06:19

标签: php singleton

<?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. 为什么两种不同的方法会产生相同的结果?

  2. 比较这两种情况,该方法在首次实例化时会起作用。

  3. (对不起,我不擅长英语,希望你能做到这一点)

2 个答案:

答案 0 :(得分:4)

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

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

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

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

答案 1 :(得分:0)

// 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();