2013-02-20 63 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

改变