1

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

1 Answer 1

7

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.

Sign up to request clarification or add additional context in comments.

14 Comments

Yes you can do new self();.
Yeah, but if it's equal to "cake" or something, then you know.. It just seems safer to use instanceof.
If it's being set to "cake" you have bigger problems ;)
if (!self::$instance) self::$instance = new self(); sufficiently solves the problem.
@Frits - Once you've already thrown in the towel and decided to use the singleton pattern, all bets are off. :) However, if (!self::$_instance) is perfectly acceptable. Since $_instance is private (it better be), it can only be null or an instance of the class. If you write code that allows it to be anything other, only then would I support a career change.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.