LoginSignup
0
2

More than 5 years have passed since last update.

PHP5.3.xまではクロージャ中にselfを使えない「Cannot access self:: when no class scope is active」

Posted at

PHP5.3.29まではクロージャの中でselfは使えないので「Fatal error: Cannot access self:: when no class scope is active 」というエラーになります。PHP各バージョンでの実行結果の比較はOnline PHP editor | output for iCEhrで見れます。

<?php

class Foo
{
    const HOGE = 1;

    public static function callClosure()
    {
        $closure = function () {
            var_dump(self::HOGE); // エラーになる
        };
        $closure();
    }
}

Foo::callClosure();

解決策としては①のようにクラス名を直接指定します。

<?php

class Foo
{
    const HOGE = 1;

    public static function callClosure()
    {
        $closure = function () {
            var_dump(Foo::HOGE); // ①
        };
        $closure();
    }
}

Foo::callClosure();
0
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
2