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