ポリモーフィズム
- 2013 8/9
- カテゴリー : クラス
日本語では多様性とかに訳されます。
もう少し具体的にいうと クラスは異なっても同じ名前のメソッドでいろんな動きを実現させる事です。
実際に行ってみます。
スーパークラス Figure コンストラクタのみをもったクラスです。
1 2 3 4 5 6 7 8 9 10 11 |
class Figure{ protected $width; protected $height; //コンストラクタ public function __construct($width,$height){ $this -> width = $width; $this -> height = $height; } } |
Figureクラスを継承したサブクラスTriangle 三角形の面積をメソッドgetAreaで計算するクラス
1 2 3 4 5 6 7 8 9 |
require_once dirname(__FILE__)."/Figure.php"; class Triangle extends Figure{ //三角形の面積 public function getArea(){ return $this -> width * $this -> height / 2; } } |
Figureクラスを継承したサブクラスSquer 四角形の面積をTriangleと同じくgetAreaで計算するクラス
1 2 3 4 5 6 7 8 |
require_once dirname(__FILE__)."/Figure.php"; class Squer extends Figure{ //四角形の面積 public function getArea(){ return $this -> width * $this -> height ; } } |
実行コード
1 2 3 4 5 6 7 |
require_once "./classes/Triangle.php"; require_once "./classes/Squer.php"; $tri = new Triangle(5,10); $squ = new Squer(5,10); echo "三角形の面積{$tri -> getArea()}<br>"; echo "四角形の面積{$squ -> getArea()}"; |
両方とも同じクラスFigureを継承し、かつgetAreaで処理を行っています。