Joshwaa
Joshwaa

Reputation: 840

PHP OOP Singleton Class

I have the code

public static function constructMe() {
    if(!$this->_instance instanceof self) {
    $this->_instance = new self();
    }
    return $this->_instance;
}

To instansiate the class, and there is a $_instance variable in the class, but I'm getting the error:

Fatal error: Using $this when not in object context

Upvotes: 1

Views: 836

Answers (1)

Halcyon
Halcyon

Reputation: 57721

You need to use

self::$_instance

Since you're in a static scope (you have no $this)

Also, make sure you declare

private static $_instance;

Also, I don't know if new self(); works You could try new __CLASS__() or just write the name of the class ..

And don't use an instanceof, just check with isset or empty (it's more accurate)

And be careful using !$var instanceof something, always write as !($var instanceof something) because you don't want to accidentally cast to a boolean.

Upvotes: 7

Related Questions