LoginSignup
1
1

More than 5 years have passed since last update.

static変数へのアクセスが思ってたのと違ったのでメモ

Posted at

php5.3以降では遅延静的束縛が使えるようになったので、getやsetのメソッドは親クラスで定義して、値をstatic変数に保持しておくということがやりたかった

<?php

class A
{
    static $hoge;

    static function get()
    {
        echo static::$hoge;
    }

    static function set($value)
    {
        static::$hoge = $value;
    }
}

class B extends A
{
}

class C extends A
{
}

B::set('b');

C::set('c');

B::get(); // 'b'が返ってきて欲しいけど'c'が返ってくる

selfじゃなくてstaticで呼べば勝手に子クラスで継承された$hogeに値が入ると思ってたけどそうじゃなかった

// Aの定義は省略

class B extends A
{
    static $hoge;
}

class C extends A
{
    static $hoge;
}

B::set('b');

C::set('c');

B::get(); // 'b'が返ってくる

子クラスで$hogeを宣言してやれば解決した

1
1
1

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
1
1