简体   繁体   English

PHP OOP Singleton Class

[英]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:要实例化 class,并且 class 中有一个$_instance变量,但我收到了错误:

Fatal error: Using $this when not in object context

You need to use你需要使用

self::$_instance

Since you're in a static scope (you have no $this )由于您在 static scope 中(您没有$this

Also, make sure you declare另外,请确保您声明

private static $_instance;

Also, I don't know if new self();另外,我不知道new self(); works You could try new __CLASS__() or just write the name of the class..作品您可以尝试new __CLASS__()或只写class的名称..

And don't use an instanceof , just check with isset or empty (it's more accurate)并且不要使用instanceof ,只需检查issetempty (更准确)

And be careful using !$var instanceof something , always write as !($var instanceof something) because you don't want to accidentally cast to a boolean.小心使用!$var instanceof something ,总是写成!($var instanceof something)因为你不想意外地转换为 boolean。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM