LoginSignup
0
0

More than 1 year has passed since last update.

【備忘録】PHP継承について

Posted at

継承とは

あるクラスで定義したプロパティやメソッドを、他のクラスに引き継ぐこと。

継承されるクラスを「親クラス(スーパークラス)」、継承するクラスを「子クラス(サブクラス)」と言う。

継承の方法

class 子クラス名 extends 親クラス { }

サンプルコード

<?php

class Human {
  protected $name;

  // 初期化処理
  public function __construct($name) {
    $this->name = $name;
  }

  //名前を返す
  public function getName() {
    return $this->name;
  }

  // 名前を表示する
  public function introduce() {
    echo $this->getName();
  }
}

  // オブジェクトを生成・初期化
  $human = new Human("tanaka");
  

  // メソッドの実行
  $human->introduce();


  // 継承されたBuchoクラス
  class Bucho extends Human {
  }

  $bucho = new Bucho("sato");
  echo "<br>";
  $bucho->introduce();

実行結果

tanaka
sato
0
0
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
0
0