LoginSignup
1
1

More than 5 years have passed since last update.

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

Last updated at Posted at 2017-04-19
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

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