Qiita Teams that are logged in
You are not logged in to any team

Log in to Qiita Team
Community
OrganizationAdvent CalendarQiitadon (β)
Service
Qiita JobsQiita ZineQiita Blog
Help us understand the problem. What is going on with this article?

php継承関係にあるクラス変数を再帰的にマージするメソッド

More than 3 years have passed since last update.
class A {
  public static $prop = array(
    "common" => 1,
    "a" => 1,
  );

  public static function getProp() {
    $parent_prop  = array();
    $ref          = new ReflectionClass(get_called_class());
    $ref_parent   = $ref->getParentClass();
    if ( $ref_parent ) {
      $parent_class = $ref_parent->getName();
      $parent_prop = $parent_class::getProp();
    }
    return array_merge($parent_prop, static::$prop);
  }
}
class B extends A {
  public static $prop = array(
    "common" => 2,
    "b" => 2,
  );
}
class C extends B {
  public static $prop = array(
    "common" => 3,
    "c" => 3,
  );
}

var_dump(A::getProp());
// array(2) {
//   ["common"]=>
//   int(1)
//   ["a"]=>
//   int(1)
// }
var_dump(B::getProp());
// array(3) {
//   ["common"]=>
//   int(2)
//   ["a"]=>
//   int(1)
//   ["b"]=>
//   int(2)
// }
var_dump(C::getProp());
// array(4) {
//   ["common"]=>
//   int(3)
//   ["a"]=>
//   int(1)
//   ["b"]=>
//   int(2)
//   ["c"]=>
//   int(3)
// }

動作確認
php5.3.29, php5.5.4, php5.6.0

metheglin
敷布団カバーと掛布団カバーを逆につけて寝ています
https://metheglin.jp/#logical
Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away