PHP クラス(オブジェクト?)、継承とオーバライド(extends、staticなど)

親メソッドの書き換えや親メソッドを使う・・・など

作成日:2018-12-14, 更新日:2019-12-23

クラスと継承(extends)の基本

class A {
  public $a = 'earth';
  
  public function getName(){
    return 'Heaven';
    // return $this->a; // 「$a='earth'」を使うとき
  }
  
  public function hello(){
    echo 'hello ' . $this->getName();
  }
}

class B extends A{
  public function getName(){
    return 'Hell';
  }
}

$hogeA = new A();
echo $hogeA->a;  // 「earth」が出力
$hogeA->hello(); // 「hello Heaven」が出力

$hogeB = new B();
$hogeB->hello(); // 「hello Hell」が出力

静的(static)

継承が絡まない場合

class A {
  public static $a = 'earth';
  
  public static function getName(){
    return 'Heaven';
    // return self::$a; // 「$a='earth'」を使うとき
  }
  
  public static function hello(){
    echo 'hello ' . self::getName();
  }
}

echo A:$a;  // 「earth」が出力
A::hello(); // 「hello Heaven」が出力

継承が絡む場合

▼継承先でオーバーライドさせる:「self」を「static」にする

class A {
  public static function getName(){
    return 'Heaven';
  }
  
  public static function hello(){
    echo 'hello ' . self::getName(); // 「self」を使う
  }
  
  public static function bye(){
    echo 'bye ' . static::getName(); // 「self」じゃなく「static」を使う
  }
}

class B extends A {
  public static function getName(){
    return 'Hell';
  }
}

B::hello(); // オーバーライドが無効で「hello Heaven」が出力
B::bye();   // オーバーライドが有効で「bye Hell」が出力
継承元 static::〇〇〇()
継承先 self::〇〇〇()

継承先で継承元のメソッドを使う

例としては微妙だけど・・・「parent」を使う。

class A {
  public static function hello(){
    echo 'hello Heaven';
  }
}

class B extends A {
  public static function hello2(){
    parent::hello();
  }
}

B::hello2(); // 「hello Heaven」が出力

staticじゃない親

▼継承元のメソッドがstaticじゃない場合・・・同じ「parent::」でOK

parent::〇〇〇();