开发者

PHP OOP singleton doesn't return object

开发者 https://www.devze.com 2023-01-27 19:28 出处:网络
Weird trouble. I\'ve used singleton multiple times but this particular case just doesn\'t want to work. Dump says that instance is null.

Weird trouble. I've used singleton multiple times but this particular case just doesn't want to work. Dump says that instance is null.

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

Core class

class Core
{
    static $instance;

    public $db;
    public $created = false;

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

    static fun开发者_运维技巧ction getInstance()
    {       
        if(!self::$instance) {
            self::$instance = new Core();
        } else {
            return self::$instance;
        }
    }

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

}

Error code

Fatal error: Call to a member function settings() on a non-object in path

It's possibly some stupid typo, but I don't have any errors in my editor. Thanks for the fast responses as always.


You need to always return the singleton object from the singleton method, here you are not because you have an else statement, so the first invocation of getInstance will not return anything:

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

Your singleton method should look like this:

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

Also, having an instance variable denoting whether an object was created is pretty much useless, because you can just compare if(self::$instance !== NULL) and you're good to go.


getInstance should always return a value -- needs to change like this:

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


In addition to needing to change your getInstance() method to:

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

...you're also trying to dereference $instance from the instance itself in the following call:

var_dump($core->instance);

You should either be checking:

var_dump($core);

or

var_dump(Core::$instance);

...which, after the $core = Core::getInstance() call, should be the same object.

0

精彩评论

暂无评论...
验证码 换一张
取 消