Perl日記

日々の知ったことのメモなどです。Perlは最近やってないです。

PHP5.3での無名関数内でのselfや$thisは解決できないから気をつけろ

ハマったのでメモ。
PHP5.4以降なら問題ないっぽい。
無名関数内でselfや$thisを使うとエラーになる。

<?php
class Hoge {
    public static function h() {
        return "hoge----!!!";
    }

    public function hh() {
        return "hogehoge----!!!";
    }
}
class Fuga extends Hoge {
    public static function f() {
        $f = function(){ return self::h(); }; // selfにはFugaを期待
        return $f();
    }

    public function ff() {
        $f = function(){ return $this->hh(); }; // $thisには$fugaを期待
        return $f();
    }
}

// ・staticメソッド
//
echo Fuga::f().PHP_EOL;
// PHP5.3の場合 エラー
// PHP Fatal error:  Using $this when not in object context in test.php on line 13
//
// PHP5.4の場合
// hoge----!!!


// ・インスタンスメソッド
$fuga = new Fuga();
echo $fuga->ff().PHP_EOL;
// PHP5.3の場合 エラー
// PHP Fatal error:  Using $this when not in object context in test.php on line 18
//
// PHP5.4の場合
// hogehoge----!!!


早く7出ないかなー。