2011-06-10 85 views
1

我的代碼PHP OOP辛格爾頓

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

要instansiate類,並且在類中的$_instance變量,但我得到的錯誤:

Fatal error: Using $this when not in object context 

回答

7

您需要使用

self::$_instance 

既然你在一個靜態的範圍是(你有沒有$this

此外,還要確保你聲明

private static $_instance; 

另外,我不知道是否new self();作品 你可以嘗試new __CLASS__()或只寫類的名稱..

也不要使用instanceof,只是issetempty(這是更準確)

檢查,並使用!$var instanceof something要小心,總是寫爲!($var instanceof something)因爲你不想意外投射到布爾值。

+2

是的,你可以做'新self();'。 – alexn 2011-06-10 21:24:21

+0

是的,但如果它等於「蛋糕」或什麼的,那麼你知道..使用instanceof似乎更安全。 – Joshwaa 2011-06-10 21:25:10

+1

如果它被設置爲「蛋糕」,你有更大的問題;) – Halcyon 2011-06-10 21:25:53