ど素人から毛を生やす。<延>

継承したクラスのstatic変数の呼び出し方

Web > PHP 2025年11月21日(最終更新:0日前)

どもです。

static変数、便利ですね。僕も大好きです。

class Paren{
        static $a = '親のstatic変数';

        static function test2(){
                var_dump(self::$a);
        }
}

class Child extends Paren{
        static $a = '子のstatic変数';

        static function test1(){
                var_dump(self::$a);
        }

}

Child::test1();
Child::test2();
実行結果
string(18) "子のstatic変数"
string(18) "親のstatic変数"

  _ , ,_  パァン
( ‘д‘)
 ⊂彡☆))Д´)

継承先を指定して実行した関数で、敢えて親のstatic変数が欲しいことなんて無いだろうが!!

class Paren{
        static $a = '親のstatic変数';

        static function test2(){
                var_dump(static::$a);
        }
}

class Child extends Paren{
        static $a = '子のstatic変数';

        static function test1(){
                var_dump(static::$a);
        }

}

Child::test1();
Child::test2();
実行結果
string(18) "子のstatic変数"
string(18) "子のstatic変数"

はい。

static変数を自身のクラス内から呼び出す場合、self::はダメです。static::を使おう。

【難しい話はこちら】PHPマニュアル 遅延静的束縛 (Late Static Bindings) 

この記事は役に立ちましたか?
  • _(:3」∠)_ 面白かった (0)
  • (・∀・) 参考になった (0)
  • (`・ω・´) 役に立った (0)