บทนำ
ใน OOP Abstract Class คือคลาสที่ ไม่สามารถสร้าง Instance (Instantiate) ได้ PHP รองรับตั้งแต่ Version 5.0
คลาสที่ประกาศด้วยคีย์เวิร์ด abstract จะกลายเป็น Abstract Class นอกจากนี้ คลาสที่มี Abstract Method อย่างน้อย 1 ตัว ก็ถือเป็น Abstract Class อัตโนมัติ
Syntax
<?php
abstract class testclass {
// abstract methods และ/หรือ concrete methods
}
?>
พยายามสร้าง Object ของ Abstract Class จะได้ Error:
$a = new testclass(); // PHP Fatal error: Cannot instantiate abstract class testclass
Abstract Method
Abstract Method มีแค่ Signature (Visibility, Arguments, Return Type) ไม่มี Body/Implementation คลาสลูกที่ Extends ต้อง Override (Implement) Abstract Methods ทั้งหมด Signature ต้องตรงกัน หากไม่ทำ จะเกิด Exception
ตัวอย่าง: ไม่ Implement ครบ
<?php
abstract class testclass {
abstract function test1();
abstract function hello();
}
class myclass extends testclass {
function test1() {
echo "Overrides parent test method";
}
// ไม่มี hello() - Error
}
$a = new myclass();
?>
ผลลัพธ์ (Error)
PHP Fatal error: Class myclass contains 1 abstract method and must therefore be declared abstract or implement the remaining methods (testclass::hello)
Abstract Method กับ Arguments
ถ้า Abstract Method มี Arguments Child ต้อง Override ด้วย Arguments จำนวนเท่าเดิม:
<?php
abstract class testclass {
abstract function hello($name, $age);
}
class myclass extends testclass {
function hello($name, $age) {
echo "My name is $name and my age is $age";
}
}
$a = new myclass();
$a->hello("Ravi", 20);
?>
ผลลัพธ์
My name is Ravi and my age is 20
Abstract Class vs Interface
| คุณสมบัติ | Abstract Class | Interface |
|---|---|---|
| Instantiate ได้ไหม | ไม่ได้ | ไม่ได้ |
| มี Concrete Methods ได้ไหม | ได้ | ไม่ได้ (PHP 8-) |
| มี Properties ได้ไหม | ได้ | ได้แค่ Constants |
| Multiple Inheritance | ไม่ได้ (extends 1 ตัว) | ได้ (implements หลายตัว) |
| Constructor | ได้ | ไม่ได้ |
| Visibility | public, protected, private | public เท่านั้น |
เมื่อไหร่ควรใช้ Abstract Class
- มี Base Implementation ที่ Share ระหว่าง Subclasses
- ต้องการ Constructor/Properties ที่ร่วมกัน
- ต้องการ Protected/Private Methods
- Hierarchy แบบ "Is-a" ที่ชัดเจน
ตัวอย่างจริง: Abstract Shape
<?php
abstract class Shape {
protected $color;
public function __construct($color) {
$this->color = $color;
}
abstract public function area(): float;
abstract public function perimeter(): float;
public function getColor(): string {
return $this->color;
}
}
class Circle extends Shape {
private $radius;
public function __construct($color, $radius) {
parent::__construct($color);
$this->radius = $radius;
}
public function area(): float {
return M_PI * $this->radius ** 2;
}
public function perimeter(): float {
return 2 * M_PI * $this->radius;
}
}
$circle = new Circle("Red", 5);
echo "Area: " . $circle->area() . "\n";
echo "Color: " . $circle->getColor() . "\n";
?>