PHP OOP Singleton类

Jos*_*waa 1 php oop singleton

我有代码

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

要实现类,并且类中有一个$_instance变量,但我收到错误:

Fatal error: Using $this when not in object context
Run Code Online (Sandbox Code Playgroud)

Hal*_*yon 7

你需要使用

self::$_instance
Run Code Online (Sandbox Code Playgroud)

因为你处于静态范围内(你没有$this)

另外,请确保您声明

private static $_instance;
Run Code Online (Sandbox Code Playgroud)

另外,我不知道是否有new self();作品您可以尝试new __CLASS__()或只写类的名称..

并且不要使用instanceof,只需检查issetempty(它更准确)

并且要小心使用!$var instanceof something,总是写为!($var instanceof something)因为你不想意外地转换为布尔值.

  • 是的你可以做`new self();`. (2认同)