2013-02-13 22 views
0

我想在函數中編譯一個mysqli變量的if語句,但我收到一個致命錯誤,聲明'使用$ this,而不是在對象上下文中...在行117上。我做錯了,我怎麼能得到的if語句在函數中工作?

代碼:

$qandaquery = "SELECT ReplyType 
        FROM Reply"; 

    $qandaqrystmt=$mysqli->prepare($qandaquery); 
    // get result and assign variables (prefix with db) 
    $qandaqrystmt->execute(); 
    $qandaqrystmt->bind_result($qandaReplyType); 
    $this->shared_result[] = $qandaReplyType; //ERROR HERE 

function ExpandOptionType($option) { 


    if('Single' == $this->shared_result){ 

... 

}else if('Multiple' == $this->shared_result){ 

... 

} 
} 
+0

你想''這個''在這裏意味着什麼開始? – deceze 2013-02-13 10:57:32

+0

你在這個領域沒有課,所以$這不起作用。 shared_result數組的初始化在哪裏?你可以請張貼這個片段嗎? – Shimu 2013-02-13 10:58:01

+0

我想你不是在課堂上工作,查看功能 – 2013-02-13 11:00:07

回答

1

您正在嘗試使用$this通用功能(不是方法)內。它應該寫入沿線的東西:

class A { 

    private $shared_result = array(); 

    public function __construct($mysqli) { 

     $qandaquery = "SELECT ReplyType FROM Reply"; 
     $qandaqrystmt = $mysqli->prepare($qandaquery); 
     $qandaqrystmt->execute(); 
     $qandaqrystmt->bind_result($qandaReplyType); 
     $this->shared_result[] = $qandaReplyType; 

    } 

    public function ExpandOptionType($option) { 

     if('Single' == $this->shared_result){ 
      ... 
     } else if('Multiple' == $this->shared_result) { 
      ... 
     } 

    } 

} 

是有道理的。請記住,$this總是指您正在使用的類的實例。在非類上下文中,它沒有任何意義。

+0

嗨,我可以問我是否需要真正使用$ this來試圖訪問函數中的$ mysqli變量以在if語句中使用。我能不能像訪問'$ qandaReplyType'一樣訪問if語句中的$ mysqli變量? – user2056342 2013-02-13 13:10:45

+0

@ user2056342,不,你不能,也沒有意義。你沒有任何意義,你可能不知道'$ this->'是什麼,所以我建議你看看[Classes and OOP](http://php.net/manual/en/)。 language.oop5.php)和[依賴注入](http://en.wikipedia.org/wiki/Dependency_injection)。 – Shoe 2013-02-13 13:24:36