PHP OOP单例不返回对象

Mis*_*iur 1 php oop singleton

奇怪的麻烦.我已经多次使用过单身,但这个特殊情况只是不想工作.转储表示该实例为空.

define('ROOT', "/");
define('INC', 'includes/');
define('CLS', 'classes/');

require_once(CLS.'Core/Core.class.php');

$core = Core::getInstance();

var_dump($core->instance);

$core->settings(INC.'config.php');
$core->go();
Run Code Online (Sandbox Code Playgroud)

核心课程

class Core
{
    static $instance;

    public $db;
    public $created = false;

    private function __construct()
    {
        $this->created = true;
    }   

    static function getInstance()
    {       
        if(!self::$instance) {
            self::$instance = new Core();
        } else {
            return self::$instance;
        }
    }

    public function settings($path = null)
    {
        ...
    }
    public function go()
    {
        ...
    }

}
Run Code Online (Sandbox Code Playgroud)

错误代码

Fatal error: Call to a member function settings() on a non-object in path
Run Code Online (Sandbox Code Playgroud)

这可能是一些愚蠢的错字,但我的编辑器中没有任何错误.感谢您一如既往的快速反应.

Jac*_*kin 9

你需要总是从singleton方法返回singleton对象,这里你不是因为你有一个else语句,所以第一次调用getInstance不会返回任何东西:

static function getInstance()
{       
    if(!self::$instance) {
        self::$instance = new Core();
    } else {
        return self::$instance;
    }
}
Run Code Online (Sandbox Code Playgroud)

你的单例方法应如下所示:

static function getInstance()
{       
    if(!self::$instance) {
        self::$instance = new Core();
    }
    return self::$instance;
}
Run Code Online (Sandbox Code Playgroud)

另外,有一个表示对象是否被创建的实例变量几乎没用,因为你可以比较if(self::$instance !== NULL)并且你很好.