2013-02-20 65 views
0

我使用$ this調用匿名函數內的成員函數。

$this->exists($str) 

PHP 5.4不給我的問題,5.3給我的問題。

的錯誤是

<b>Fatal error</b>: Using $this when not in object context in 

這裏是我的代碼

class WordProcessor 
{ 

private function exists($str) 
{ 
//Check if word exists in DB, return TRUE or FALSE 
return bool; 
} 

private function mu_mal($str) 
{ 

    if(preg_match("/\b(mu)(\w+)\b/i", $str)) 
    { $your_regex = array("/\b(mu)(\w+)\b/i" => "");  
     foreach ($your_regex as $key => $value) 
      $str = preg_replace_callback($key,function($matches)use($value) 
      { 
       if($this->exists($matches[0])) //No problems in PHP 5.4, not working in 5.3 
        return $matches[0]; 
       if($this->exists($matches[2])) 
        return $matches[1]." ".$matches[2]; 
       return $matches[0]; 
      }, $str); 
    } 
    return $str; 
} 

} 

回答

4

您使用$this這是在一個單獨的環境中執行一個封閉的內部。

在您的mu_mal函數的開頭,您應該聲明$that = $this(或類似$wordProcessor的內容,以便更清楚地瞭解變量的含義)。然後,在您的preg_replace_callback關閉內部,您應該在關閉內部添加use ($that)和參考$that而不是$this

class WordProcessor 
{ 

    public function exists($str) 
    { 
     //Check if word exists in DB, return TRUE or FALSE 
     return bool; 
    } 

    private function mu_mal($str) 
    { 
     $that = $this; 

     if(preg_match("/\b(mu)(\w+)\b/i", $str)) 
     { 
      $your_regex = array("/\b(mu)(\w+)\b/i" => "");  
      foreach ($your_regex as $key => $value) 
       $str = preg_replace_callback($key,function($matches)use($value, $that) 
       { 
        if($that->exists($matches[0])) //No problems in PHP 5.4, not working in 5.3 
         return $matches[0]; 
        if($that->exists($matches[2])) 
         return $matches[1]." ".$matches[2]; 
        return $matches[0]; 
       }, $str); 
     } 
     return $str; 
    } 
} 

注意,你不得不暴露exists到類的公共API(這是我在上面所做的)

這種行爲是PHP 5.4

改變