PHP interface และ polymorphism



interface คือ “สัญญา” — รายการเมธอดที่คลาสต้องมี โดยไม่กำหนดว่าทำยังไง ประโยชน์คือทำให้โค้ดของเราพึ่งพา “ความสามารถ” ไม่ใช่ “คลาสเฉพาะตัว”

ประกาศและ implement

<?php
declare(strict_types=1);

interface PaymentGateway
{
    public function charge(int $amountSatang, string $currency): string;
    public function refund(string $transactionId): bool;
}

class PromptPayGateway implements PaymentGateway
{
    public function charge(int $amountSatang, string $currency): string
    {
        // ยิงไป API PromptPay จริง ...
        return 'pp_' . bin2hex(random_bytes(6));
    }

    public function refund(string $transactionId): bool
    {
        return true;
    }
}

class StripeGateway implements PaymentGateway
{
    public function charge(int $amountSatang, string $currency): string
    {
        return 'ch_' . bin2hex(random_bytes(6));
    }

    public function refund(string $transactionId): bool
    {
        return true;
    }
}
  • interface มีแต่ลายเซ็นเมธอด (ไม่มี body) — เมธอดทุกตัวเป็น public เสมอ
  • คลาสที่ implements PaymentGateway ต้อง มีเมธอดครบตามที่สัญญา ไม่งั้น error ตอนโหลดคลาส

polymorphism — จุดที่ interface มีค่า

โค้ดที่ทำงานจริงรับ PaymentGateway (interface) ไม่ใช่คลาสเฉพาะ:

<?php
class CheckoutService
{
    public function __construct(private PaymentGateway $gateway) {}

    public function pay(int $amountSatang): string
    {
        $txId = $this->gateway->charge($amountSatang, 'THB');
        echo "ชำระเงินสำเร็จ: $txId\n";
        return $txId;
    }
}

// สลับ gateway ได้โดยไม่ต้องแก้ CheckoutService เลย
$checkout = new CheckoutService(new PromptPayGateway());
$checkout->pay(50000);

$checkout2 = new CheckoutService(new StripeGateway());
$checkout2->pay(50000);

CheckoutService ไม่รู้จักและไม่สนว่าเป็น gateway ตัวไหน ขอแค่ทำตามสัญญา PaymentGateway ได้ — ผลคือ:

  • ทดสอบง่าย — สร้าง FakeGateway implements PaymentGateway ป้อนตอนเทสต์
  • เพิ่มของใหม่ง่าย — gateway ตัวที่ 3 ไม่กระทบโค้ดเดิม
  • คู่กันหลวม ๆ — แต่ละส่วนเปลี่ยนแยกกันได้

implement หลาย interface

คลาสเดียว implements ได้หลาย interface (ต่างจาก extends ที่ได้แม่เดียว):

<?php
interface Jsonable
{
    public function toJson(): string;
}

interface Cacheable
{
    public function cacheKey(): string;
}

class Article implements Jsonable, Cacheable
{
    public function __construct(
        public int $id,
        public string $title,
    ) {}

    public function toJson(): string
    {
        return json_encode(
            ['id' => $this->id, 'title' => $this->title],
            JSON_UNESCAPED_UNICODE,
        );
    }

    public function cacheKey(): string
    {
        return "article:{$this->id}";
    }
}

ฟังก์ชันที่ต้องการแค่ “แปลงเป็น JSON ได้” รับ Jsonable ก็พอ ไม่ต้องสนว่าเป็น Article หรืออะไร

<?php
function dump(Jsonable $item): void
{
    echo $item->toJson(), "\n";
}

interface สืบทอดกันได้

<?php
interface Readable
{
    public function read(): string;
}

interface Writable
{
    public function write(string $data): void;
}

interface ReadWritable extends Readable, Writable
{
}

class File implements ReadWritable
{
    // ต้องมีทั้ง read() และ write()
    public function read(): string { return 'ข้อมูล'; }
    public function write(string $data): void { /* ... */ }
}

constant ใน interface

<?php
interface HttpStatus
{
    const int OK = 200;
    const int NOT_FOUND = 404;
    const int SERVER_ERROR = 500;
}

echo HttpStatus::NOT_FOUND, "\n";   // 404

(PHP 8.3 ให้ใส่ชนิดให้ constant ได้ — const int OK = 200;)

interface เทียบ abstract class

interfaceabstract class
body ของเมธอดไม่มีเลยมีได้ (แชร์โค้ด)
propertyไม่มี (มีแต่ constant)มีได้
คลาสหนึ่งใช้ได้กี่ตัวหลายตัวตัวเดียว
ใช้เมื่อกำหนด “ความสามารถ” ที่คลาสหลากหลายมีร่วมกันคลาสที่เกี่ยวข้องกันจริง ๆ มีโค้ดร่วม

แนวทางที่นิยม: เขียน interface สำหรับสัญญา แล้วมี abstract class เป็นตัวช่วย implement บางส่วน (เช่น AbstractPaymentGateway implements PaymentGateway ที่ทำ refund() เวอร์ชันมาตรฐานไว้)

type ที่มีอยู่แล้วในตัว PHP

PHP มี interface ในตัวที่ใช้ประโยชน์ได้:

  • Stringable — คลาสมี __toString() (PHP เติมให้อัตโนมัติถ้ามีเมธอดนั้น)
  • Countable — ให้ count($obj) ทำงาน
  • IteratorAggregate / Iterator — ให้ foreach ($obj) ทำงาน
  • JsonSerializable — คุมว่า json_encode($obj) ได้อะไร
  • ArrayAccess — ให้ $obj['key'] ทำงาน
<?php
class Cart implements Countable
{
    private array $items = [];

    public function add(string $item): void { $this->items[] = $item; }

    public function count(): int { return count($this->items); }
}

$cart = new Cart();
$cart->add('เสื้อ');
$cart->add('กางเกง');
echo count($cart), "\n";      // 2

เรื่องที่คนมักพลาด

  • ใส่ visibility อื่นที่ไม่ใช่ public ในเมธอด interface — ไม่ได้ ทุกเมธอดเป็น public
  • type hint ต่อคลาสเฉพาะทั้งที่ควรเป็น interface เช่น function pay(StripeGateway $g) — มัดตัวเองกับ Stripe ทันที ควรเป็น PaymentGateway
  • implements แล้ว signature ไม่ตรงเป๊ะ เช่น interface บอก charge(int $x) แต่คลาสเขียน charge(string $x) — error
  • ยัดทุกอย่างไว้ใน interface เดียวใหญ่ ๆ — คลาสต้อง implement เมธอดที่ไม่เกี่ยวข้อง แยกเป็น interface เล็ก ๆ ตามความสามารถ (Interface Segregation)
  • สับสนว่า interface สร้าง new ได้ — ไม่ได้ มันไม่มี implementation
  • ประกาศ property ใน interface — ไม่ได้ มีแต่ constant กับลายเซ็นเมธอด (PHP 8.4 เพิ่มความสามารถ property hook ใน interface แต่นั่นเป็นเรื่องเฉพาะ)

สรุป

  • interface = รายการเมธอดที่คลาสต้องมี ไม่มี body ทุกเมธอด public
  • คลาส implements ได้หลาย interface, interface extends interface อื่นได้หลายตัว
  • type hint ต่อ interface → สลับ implementation ได้โดยไม่แก้โค้ดที่ใช้ (polymorphism, ทดสอบง่าย)
  • interface = “ความสามารถ”, abstract class = “ฐานร่วมที่มีโค้ด” — มักใช้คู่กัน
  • PHP มี interface ในตัว เช่น Countable, Stringable, JsonSerializable

บทถัดไปว่าด้วย trait — วิธีแชร์เมธอด (พร้อม body) ข้ามคลาสที่ไม่มีความสัมพันธ์แบบสืบทอด