PHP 5.3$与PHP 5.4相比
我正在使用$this调用匿名函数中的成员函数PHP 5.3$与PHP 5.4相比,php,Php,我正在使用$this调用匿名函数中的成员函数 $this->exists($str) PHP5.4不会给我带来问题,5.3会给我带来问题 错误是 <b>Fatal error</b>: Using $this when not in object context in 您正在一个闭包中使用$this,闭包在一个单独的上下文中执行 在函数的开头,您应该声明$that=$this(或者类似$wordProcessor的内容,以便更明确地说明变量是什么)。然后,在
$this->exists($str)
PHP5.4不会给我带来问题,5.3会给我带来问题
错误是
<b>Fatal error</b>: Using $this when not in object context in
您正在一个闭包中使用
$this
,闭包在一个单独的上下文中执行
在函数的开头,您应该声明$that=$this
(或者类似$wordProcessor
的内容,以便更明确地说明变量是什么)。然后,在preg\u replace\u回调
的闭包中,您应该添加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;
}
}
注意,您必须将存在
公开给类的公共API(我在上面已经做过)
此行为在PHP5.4中发生了更改,您使用的是在单独上下文中执行的闭包内部的
$This
在函数的开头,您应该声明$that=$this
(或者类似$wordProcessor
的内容,以便更明确地说明变量是什么)。然后,在preg\u replace\u回调
的闭包中,您应该添加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;
}
}
注意,您必须将存在
公开给类的公共API(我在上面已经做过)
这种行为在PHP5.4中发生了更改