LoginSignup
9
6

More than 5 years have passed since last update.

【PHP】親クラスのメソッドをオーバーライドする。

Posted at

こんにちは。

ちょっと検索すると、なんやかんやで難しい言葉(単語)を並べ
余計に混乱してしまうように感じるのは僕だけでしょうか。

オーバーライドを調べた時にこの現象に陥りました。。

利用法は

継承した子クラスで、親クラスで定義されたメソッドを再定義する。

上書きですね。

書き方

class Parentclass {
    public function speak() {
        return "I'm Parent!";
    }
}        

class  Childclass extends Parentclass {
    public function speak(){
        return "I'm Child!" ;
    }
}

//出力確認
$speak = new Parentclass() ;
echo $speak -> speak() ; //I'm Parent!

$speak = new Childclass() ;
echo $speak -> speak() ; //I'm Child!


extendsで継承してその後同じ名前でメソッドを定義してあげれば
オーバーライドの完了ですね

これだけだと何に使うのかわかりませんが
親クラスがもっと大きく継承されているクラスが増えると必要になるのかななんて考えてます

それではこれからも宜しくお願いします
9
6
1

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
9
6