LoginSignup
2
1

More than 3 years have passed since last update.

コードでわかるクラス継承入門

Last updated at Posted at 2020-09-18

既存のクラスを基にして拡張したり変更を加えた新しいクラスを作ることを継承するという
きっとこの記事にたどり着いたということはこれだけじゃピンとこなかったはず。。。
早速コードで見ていきたい

example.php
<?php
class ParentClass
{
    public $test1 = 'テストプロパティ1';
    public $test2 = 'テストプロパティ2';
    public function getParentData()
    {
        return 'this is your parent';
    }
    public function show()
    {
        return $this->test1 . ' ' . $this->test2;
    }
}
class ChildClass extends ParentClass
{
    public $test1 = 'テストプロパティ3';
    public function getChildData()
    {
        return 'this is your child';
    }
    public function show()
    {
        return $this->test1 . ' ' . $this->test2;
    }
}
$child = new ChildClass();
echo $child->getParentData();
echo $child->getChildData();
$parent = new ParentClass();
echo $parent->show();
echo $child->show();

実行結果は

this is your parent
this is your child
テストプロパティ1 テストプロパティ2
テストプロパティ3 テストプロパティ2

となります
親クラスを継承することで子クラスから親クラスのプロパティやメソッドを引き継げる
多用すると親クラスの変更などによって予期せぬ結果が出ることがあるので
頭は体の一部のように子クラスは親クラスの一種といえない場合には使わない方がいい

オーバーライド
クラスを継承して同じメソッドを定義した場合は子クラスが優先され上書きされる

そのため上の例では$test1が子クラスでは上書きされている

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