はじめに
ポリモーフィズムについてまとめる
ポリモーフィズムとは
同名のメソッドで異なる挙動を実現する。
多態性と訳される。
参考コード
Figuer.php
class Figure
{
protected float $width;
protected float $height;
public function __construct(float $width, float $height)
{
$this->width = $width;
$this->height = $height;
}
public function getArea(): float
{
return 0;
}
}
Triangle.php
require_once 'Figure.php';
class Triangle extends Figure
{
public function getArea(): float
{
return $this->width * $this->height / 2;
}
}
Square.php
require_once 'Figure.php';
class Square extends Figure
{
public function getArea(): float
{
return $this->width * $this->height;
}
}
polymo.php
require_once 'Triangle.php';
require_once 'Square.php';
$tri = new Triangle(5, 10);
$squ = new Square(5, 10);
print "三角形の面積: " . $tri->getArea() . "\n"; // 三角形の面積: 25
print "四角形の面積: " . $squ->getArea() . "\n"; // 四角形の面積: 50
Figure
クラスを継承する2つのサブクラスTriangle
とSquare
で同名のgetArea
メソッドをオーバーライドし、それぞれ三角形と四角形の面積を求めている。
複数のクラスで同じ名前のメソッドを定義している。
ポリモーフィズムのメリット
同じ目的の機能を呼び出すために異なる名前(命令)を覚えなくても良い点。