Polymorphism มาจากคำภาษา希臘 Poly (หลาย) และ morphism (รูปแบบ) ใน OOP Polymorphism คือรูปแบบที่เมธอดในคลาสต่างๆ ที่ทำงานคล้ายกันควรมีชื่อเดียวกัน Polymorphism เป็นรูปแบบ OOP ที่ให้คลาสหลายๆ คลาสที่มีฟังก์ชันต่างกัน สามารถ implement หรือ share common interface ได้ โค้ดที่เขียนในคลาสต่างๆ ไม่สนว่าจะเป็นคลาสไหน เพราะใช้งานแบบเดียวกัน เพื่อให้แน่ใจว่าคลาสปฏิบัติตาม polymorphism สามารถเลือกใช้ abstract class หรือ interface ได้
มาลอง implement polymorphism ด้วย interface
ตัวอย่าง
<?php
interface Machine {
public function calcTask();
}
class Circle implements Machine {
private $radius;
public function __construct($radius){
$this->radius = $radius;
}
public function calcTask(){
return $this->radius * $this->radius * pi();
}
}
class Rectangle implements Machine {
private $width;
private $height;
public function __construct($width, $height){
$this->width = $width;
$this->height = $height;
}
public function calcTask(){
return $this->width * $this->height;
}
}
$mycirc = new Circle(3);
$myrect = new Rectangle(3,4);
echo $mycirc->calcTask();
echo $myrect->calcTask();
?>
ผลลัพธ์
28.274 12
คำอธิบาย
Interface "Machine" บังคับคลาสที่ implement ต้องมีเมธอด calcTask() Circle และ Rectangle implement interface เดียวกัน แต่ calcTask() ทำงานต่างกัน (พื้นที่วงกลม vs สี่เหลี่ยม) Polymorphism ทำให้เราเรียก calcTask() ได้โดยไม่ต้องรู้รายละเอียดการคำนวณของแต่ละคลาส