class内でpreg_replace_callbackを使う

11月 15th, 2009 by admin Leave a reply »

Class内でpreg_replace_callbackを使うのにとっても手こずったのでメモ。
phpマニュアル(http://php.net/manual/ja/function.preg-replace-callback.php)によれば以下のようです。

<?php
class myClass{
    public function parsetext($text){
        // parses text and sets literals A - C to lower case
        // this works
        return preg_replace_callback('|([a-c])|i', 'myClass::preg_tolower', $text);
    }
    public function parsefail($text){
        // parses text and sets literals A - C to lower case
        // this fails
        return preg_replace_callback('|([a-c])|i', 'self::preg_tolower', $text);
    }
 
    private static function preg_tolower($matches){
        return strtolower($matches[1]);
    }
}
 
$parser = new myClass;
echo $parser->parsetext('ABCDEFGH');
// echoes abcDEFGH
 
echo $parser->parsefail('ABCDEFGH');
// throws the error
?>

“self::preg_tolower”の他に

array($this,"preg_tolower")

と書いてもいいようです。

しかし、この手によく出てくる参照渡し。
いまだに使ったこともなく、理解してないw

Advertisement

コメントを残す