[英]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
,只需检查isset
或empty
(更准确)
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.