[PHP] Interface มีไว้ทำอะไร?

มาถึงคราวของ Interface หลังจากจบบทความ Abstract class ไป โดยตัว Interface จะมีความแตกต่างตรงที่ function ทุกตัวที่อยู่ในนี้ต้องเป็น public และ abstract function ทั้งหมด ซึ่งหน้าที่ของ Interface คือการกำหนดความสามารถบางอย่างให้กับ Class ที่ implements Interface ไปใช้ ซึ่งสามารถ implements ได้มากกว่า 1 Interface

มาดูตัวอย่างโค้ดกัน โค้ดชุดนี้นำมาจากเว็บ W3Schools Online Web Tutorials โดยในโค้ดจะเป็น class เกี่ยวกับสัตว์ Interface Animal บอกว่า สัตว์สามารถทำเสียงได้ แต่จะทำเสียงอะไรก็ขึ้นกับ class ของสัตว์ที่ implements ไปนั่นเอง

<?php
// Interface สัตว์บอกว่าสัตว์ทำเสียงร้องได้
interface Animal {
  public function makeSound();
}

// Class definitions
class Cat implements Animal {
  public function makeSound() {
    echo " เมี้ยว ";
  }
}

class Dog implements Animal {
  public function makeSound() {
    echo " โฮ่ง ";
  }
}

class Mouse implements Animal {
  public function makeSound() {
    echo " จี๊ด ";
  }
}

// สร้าง object ของ class สัตว์ต่าง ๆ
$cat = new Cat();
$dog = new Dog();
$mouse = new Mouse();
$animals = array($cat, $dog, $mouse);

// เอามาวนลูปเรียก function makeSound()
foreach($animals as $animal) {
  $animal->makeSound();
}
?>

จากตัวอย่างโค้ดจะเห็นว่าการทำงานของ function จะแตกต่างกันไปแล้วแต่เราจะเขียนว่า class นั้นเรียกใช้ function แล้วให้ทำอะไร

จุดประสงค์หลัก ๆ ก็ยังคงเป็น guideline ให้กับ class ที่ implements ไป แต่ส่วนมาก interface จะใช้เพื่อกำหนดความสามารถที่เฉพาะเจาะจงอย่างใดอย่างหนึ่ง จะไม่ซับซ้อนนัก

มาดูตัวอย่างที่ใช้งานจริงกันบ้างจาก Laravel framework โค้ดตรงไปตรงมา อ่านง่ายมาก
https://github.com/laravel/framework/blob/8.x/src/Illuminate/Contracts/Support/Arrayable.php

อ้างอิง: PHP OOP Interfaces (w3schools.com)

ความคิดเห็น

โพสต์ยอดนิยมจากบล็อกนี้

[Blue Archive] รวมล็อบบี้ความทรงจำ (Live2D)

[Blue Archive] รีวิวมารินะ (Marina)

[Blue Archive] รีวิวชินัตสึ (Chinatsu)

[Blue Archive] รีวิวโฮชิโนะ (Hoshino)

[Blue Archive] รีวิวจุนโกะ (Junko)