[英]PHP5 what's wrong with my syntax?
我以前從未開發過,我有點疑惑,我的語法有什么問題嗎?
private static $instance; //holder of Mongo_Wrapper
public $connected = true;
private $mongo = null; // The mongo connection affiliation
private $database = null; // The database we are working on
有了這個功能:
public function mongo_connect($db_name) {
if (! self::connected) {
$this->mongo = new Mongo;
//TODO: error handle this whole sharade: throw new Kohana_Database_Exception('Cant connect', NULL, 503);
$this->connected = true;
}
$this->database = $this->mongo->$db_name; //set the database we are working on
return $connected;
}
對不起,wmd-editor正在給我發布代碼。
謝謝!
編輯: $ connected不是靜態的,問題是它無法使用static或$ this。 此外,這是一個單身人士課程,我不知道這是否重要。
編輯:這是代碼的其余部分,這是self,並且可以正常工作:
public static function singleton($db_name) {
if (!isset(self::$instance)) {
$c = __CLASS__;
$this->$instance = new $c;
}
self::mongo_connect($db_name);
return self::$instance;
}
enter code here
if (! self::connected) {
可能是你錯誤的原因。 僅在嘗試訪問靜態類成員(未連接的靜態成員)時才使用self,並且必須在開始時使用$符號,否則將要求一個類常量。 所以你要么必須聲明連接為靜態,要么使用$ this->來訪問它。
在PHP手冊中查看靜態類成員 !
在編寫這樣的代碼之前,你應該真正嘗試理解OOP的工作原理。 PHP告訴您不能使用$ this,因為您不在對象上下文中 ,這意味着您從未使用new創建對象實例。
也許PHP OOP Basics會幫助你。
不幸的是,PHP允許你靜態調用實際上沒有的方法,這可能導致錯誤。 但是遲早(可能更快),您仍然需要了解OOP基礎知識,因此在嘗試編寫可用於生產性用途的代碼之前,請嘗試一些簡單的類。
如果您在此問題上需要進一步的幫助,請告訴我們您如何調用connect方法!
那里我們有您的問題。 你正在做以下事情:
self::mongo_connect($db_name);
這意味着“靜態調用mongo_connect”。 你真正需要做的是:
self::$instance->mongo_connect();
這相當於“在自我的單例實例上調用mongo_connect”。
但請仔細看看基本的PHP教程,因為你在代碼中所做的事情大多是錯誤的......
$this->$instance = new $c;
在很多方面都是錯誤的……不僅是因為您在靜態上下文中使用了$ this,而且還因為您將創建的實例分配給名稱為*的類成員包含在 $ instance中,這似乎是空......不知道這實際上是如何工作的......
self
應與靜態成員一起使用(使用$this->connected
而不是self::connected
)。
UPDATE
private static function mongo_connect($db_name, $instance)
{
if (!$instance->connected) {
....
}
...
return $instance->connected;
}
public static function singleton($db_name) {
if (!isset(self::$instance)) {
$c = __CLASS__;
self::$instance = new $c;
}
self::mongo_connect($db_name, self::$instance );
return self::$instance;
}
x3ro是正確的。 最后還需要$ this-> connected語法:
return $this->connected;
如果在使用$ this-> connected時收到錯誤消息,那是因為您的函數不是類上的方法,而是全局函數。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.