0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

【PHP】継承とオーバーライドについて

Last updated at Posted at 2021-09-16

基礎の基礎に戻ってみました。

継承とは

すでに存在しているクラスを元にして、新しいクラスを作ること
元のクラスの事を親クラス、基底クラスと呼びます。
新しいクラスは子クラスと呼んでます。

継承することのメリット

親クラスで定義した関数を、子クラスでも同じように使用することができます。
これによって、同じような処理を複数書かなくて良くなります。
+コードの可読性も上がるので、メンテナンスがしやすくなります。

継承の使い方

class 子クラス名 extends 親クラス名{}という形で継承することができます。

<?php
// 親クラス
class ParentClass {
  public function test(){
    print '親クラスのメソッドです'."\n";
  }
}

// 子クラス 
class ChildClass extends ParentClass {
  
}

$a = new ChildClass();
echo $a->test();

//出力結果///////
親クラスのメソッドです
?>

オーバーライド とは

子クラスが親クラスの関数を上書きすること
継承をしていることが条件です。
親クラスと同名の関数を子クラスでも定義してあげることによって、オーバーライドできます。(※引数も合わせること)

オーバーライド のメリット

1つの関数名で、クラスに応じて適切な処理(関数)を行わせることができます。

使用例

<?php
// 親クラス
class ParentClass {
  public function output(){
    print '親クラスのメソッドです'."\n";
  }
}

// 子クラス 
class ChildClass extends ParentClass {
  public function output(){
    print "子クラスのメソッドが親クラスをオーバーライドしました"; 
  }
}

$test = new ParentClass();
$test->output();

$test2 = new ChildClass();
$test2->output();
?>
////出力結果//////
親クラスのメソッドです
子クラスのメソッドが親クラスをオーバーライドしました

継承をしているので、関数名が被ってしまうとシステム側で「どっち実行すればいいの?」ってなりそうですが大丈夫です。

オーバーライドの使い方

例えば、複数のクラスがあって、1つだけ別の処理をさせたい場合などに使えます。

<?php
// 4つのクラスでは、親クラスの処理をそのまま使いたい
class ParentClass {
  public function duplicateCheck($id){
    return [];
  }
}

// 1つのクラスだけ、DBの重複チェックをしたい
class ChildClass extends ParentClass {
  public function duplicateCheck($id){
      return DB::findxx($id);
  }
?>

こういった場合に使うことができます。

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?