PHP类扩展了Singleton模式

时间:2014-02-24 17:54:25

标签: php

class singleton:

class Singleton
{
    private static $_myself;

    private function __construct(){}

    public static function getInstance()
    {
        if(!isset(self::$_myself))
        {
            $obj = __CLASS__;
            self::$_myself = new $obj;
        }
        return self::$_myself;
    }
}

我的班级:

 class MyApp extends Singleton
    {
        public function show()
        {
            echo 'show';
        }
    }
    MyApp::getInstance()->show();

但无法正常工作,此错误: 调用未定义的方法Singleton :: show() 有人可以帮帮我吗?

3 个答案:

答案 0 :(得分:3)

因为您正在返回Singleton类(正如您可以通过错误看到的那样),但应该返回MyApp类。您可以使用PHP 5.3中引入的后期静态绑定方法get_called_class()来完成此任务:

public static function getInstance()
{
    if(!isset(self::$_myself))
    {
        //__CLASS__ = Singleton | get_called_class() = MyApp
        $obj = get_called_class(); 
        self::$_myself = new $obj;
    }
    return self::$_myself;
}

答案 1 :(得分:2)

self返回实际的类实例(在这种情况下为Singleton),因此没有方法show。但您可以使用static代替selfDifferences)并将$_myself从私有更改为受保护,以便在子类中可以访问。

class Singleton
{
    protected static $_myself;

    private function __construct(){}

    public static function getInstance()
    {
        if(!isset(static::$_myself))
        {
            static::$_myself = new static;
        }
        return static::$_myself;
    }
}

答案 2 :(得分:-1)

问题在于

$obj = __CLASS__;
self::$_myself = new $obj;

您创建了类Singleton的新实例,而不是类MyApp的实例,因此该方法不可用。

现在h2ooooooo的答案比我编辑的要快,请看他的答案,而不是__CLASS__