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

1 に答える 1

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 で変更されました。

于 2013-02-20T20:43:33.150 に答える