手続き型ではなく、オブジェクト指向で書く利点として、コードの保守性が挙げられます。
手続き型では、似たようなコードがあると、
「あー、またあのコードか。じゃあコピペして少し変えちゃえ」という考え方が当然でてきます。
(そういう風だとプログラミング能力は上達しないのですが、時間的に、人間的にそうなってしまいがちなのは事実だと思います。)
そんな中で、似たようなものがあるのならば、classの内容を引き継ぎ(継承)し、再びまたclassを定義していけば、簡単に再利用でき、
保守性も増します。今回は、四角形の面積と三角形の面積を出すということを考えていきたいと思います。11月8日記事
目次
値のチェックは継承したいが、計算方法は三角形と四角形でそれぞれ違うので、違うようにしたい。
ということでHwcheckというクラスを作っておき、別ファイルで、三角形のクラス、四角形のクラスを作っていきます。
スーパークラスをまずは作っていきます。(元となるクラスをスーパークラスという。親クラス、基底クラスともいう。)
Hwcheck.php
<?php class Hwcheck{ protected $width;/*現在のクラスとサブクラスからのみアクセス許可のためprotectedを使用*/ protected $height;/*現在のクラスとサブクラスからのみアクセス許可のためprotectedを使用*/ public function __construct(){ $this->width = "値が不正です。"; $this->height = "値が不正です。"; } public function getWidth(){ return $this->width; } public function setWidth($width){ if(is_numeric($width) && $width > 0){ $this->width = $width; } } public function getHeight(){ return $this->height; } public function setHeight($height){ if(is_numeric($height) && $height > 0){ $this->height = $height; } } } ?>
Triangle.php
<?php require ('Hwcheck.php'); class Triangle extends Hwcheck{/*Hwcheckを継承したいからextents Hwcheckと書く。*/ public function getArea(){ if($this->width === "値が不正です。" || $this->height === "値が不正です。"){ return "widthかheightのどちらかが値が不正です。"; }else{ return "面積は".($this->getWidth() * $this->getHeight() / 2)."です。"; } } } ?>
三角形の呼び出し(なんでもいいよ.php)
<?php require ("../class/Triangle.php"); $res = new Triangle(); $res->setWidth(40); $res->setHeight(10); print $res->getArea(); ?>
Hwcheck.php
三角形のものを使いまわし。
Rectangle.php
<?php require ('Hwcheck.php'); class Rectangle extends Hwcheck{/*Hwcheckを継承したいからextents Hwcheckと書く。*/ public function getArea(){ if($this->width === "値が不正です。" || $this->height === "値が不正です。"){ return "widthかheightのどちらかが値が不正です。"; }else{ return "面積は".$this->getWidth() * $this->getHeight()."です。"; } } } ?>
四角形の呼び出し(なんでもいいよ2.php)
<?php require ("../class/Rectangle.php"); $res1 = new Rectangle(); $res1->setWidth(30); $res1->setHeight(60); print $res1->getArea(); ?>
※Hwcheckのheighとwidthをprivateからprotectedに変えました。
これで、三角形の面積プログラムから四角形の面積プログラムを新たに作りたい!という場合にHwcheckの内容をextendsを使って継承していけばコードは少なくて済みます。これが継承の概念です。
以上