PHP trait — ใช้โค้ดซ้ำข้ามคลาส



PHP สืบทอดได้แม่เดียว (single inheritance) แต่บางทีมีเมธอดชุดหนึ่งที่หลายคลาส “ไม่เกี่ยวกัน” อยากใช้ร่วม — เช่น การ log, การนับเวลา, การแปลงเป็นอาร์เรย์ trait แก้ปัญหานี้

trait พื้นฐาน

<?php
declare(strict_types=1);

trait Timestampable
{
    public ?DateTimeImmutable $createdAt = null;
    public ?DateTimeImmutable $updatedAt = null;

    public function touch(): void
    {
        $now = new DateTimeImmutable();
        $this->createdAt ??= $now;
        $this->updatedAt = $now;
    }

    public function age(): int
    {
        return $this->createdAt
            ? (new DateTimeImmutable())->diff($this->createdAt)->days
            : 0;
    }
}

class Article
{
    use Timestampable;

    public function __construct(public string $title) {}
}

class Comment
{
    use Timestampable;

    public function __construct(public string $body) {}
}

$a = new Article('เรียน PHP');
$a->touch();
echo $a->updatedAt->format('H:i:s'), "\n";

Article กับ Comment ไม่มีความสัมพันธ์อะไรกัน แต่ทั้งคู่ use Timestampable; แล้วได้ property + เมธอดชุดนั้นมาเหมือนก็อปโค้ดไปวาง (แต่อยู่ที่เดียว แก้ที่เดียว)

ใช้หลาย trait

<?php
trait Loggable
{
    public function log(string $message): void
    {
        echo '[' . static::class . '] ' . $message . "\n";
    }
}

trait Identifiable
{
    public readonly string $uuid;

    public function initId(): void
    {
        $this->uuid = bin2hex(random_bytes(8));
    }
}

class Order
{
    use Timestampable, Loggable, Identifiable;

    public function __construct()
    {
        $this->initId();
        $this->touch();
        $this->log("สร้างออเดอร์ {$this->uuid}");
    }
}

new Order();
// [Order] สร้างออเดอร์ 3f9a1c...

เมื่อชื่อเมธอดชนกัน

ถ้าสอง trait มีเมธอดชื่อเดียวกัน PHP จะ error ให้เราตัดสินด้วย insteadof และเปลี่ยนชื่ออีกตัวด้วย as:

<?php
trait FileLogger
{
    public function log(string $m): void { echo "ไฟล์: $m\n"; }
}

trait ConsoleLogger
{
    public function log(string $m): void { echo "จอ: $m\n"; }
}

class Service
{
    use FileLogger, ConsoleLogger {
        FileLogger::log insteadof ConsoleLogger;   // ใช้ของ FileLogger เป็นหลัก
        ConsoleLogger::log as logToConsole;        // ของ ConsoleLogger เปลี่ยนชื่อ
    }
}

$s = new Service();
$s->log('บันทึกแล้ว');           // ไฟล์: บันทึกแล้ว
$s->logToConsole('แจ้งเตือน');   // จอ: แจ้งเตือน

as ยังใช้เปลี่ยน visibility ได้: someMethod as protected;

trait เรียกเมธอด/property ที่คลาสต้องมี

trait “คาดหวัง” ได้ว่าคลาสที่ใช้มันจะมีบางอย่าง — ประกาศเป็น abstract ใน’trait เพื่อบังคับ:

<?php
trait Sluggable
{
    abstract public function getTitle(): string;

    public function getSlug(): string
    {
        $title = mb_strtolower($this->getTitle());
        return preg_replace('/[^\p{L}\p{N}]+/u', '-', trim($title));
    }
}

class BlogPost
{
    use Sluggable;

    public function __construct(private string $title) {}

    public function getTitle(): string
    {
        return $this->title;
    }
}

echo (new BlogPost('เรียน PHP OOP'))->getSlug(), "\n";   // เรียน-php-oop

ถ้า BlogPost ลืม getTitle() จะ error ตอนโหลดคลาส

trait ลำดับความสำคัญ

เมื่อชื่อชนกันระหว่าง “คลาสแม่ / trait / คลาสเอง”:

เมธอดในคลาสเอง  >  เมธอดจาก trait  >  เมธอดจากคลาสแม่

คลาสเองเขียนทับ trait ได้เสมอ และ trait เขียนทับของแม่

trait เทียบ interface เทียบ inheritance

ให้อะไรใช้เมื่อ
interfaceสัญญา (ไม่มี body)ต้องการ polymorphism / type hint
traitโค้ด (มี body) แปะใส่คลาสแชร์ implementation ข้ามคลาสที่ไม่เกี่ยวกัน
extendsโค้ด + ตัวตน (is-a)ความสัมพันธ์ “เป็นชนิดหนึ่งของ” จริง ๆ

คู่ที่นิยม: interface บอกว่าทำอะไรได้ + trait ให้ implementation เริ่มต้น

<?php
interface HasTimestamps
{
    public function touch(): void;
}

// คลาสที่ implements HasTimestamps ใช้ trait Timestampable ประหยัดโค้ด
class Product implements HasTimestamps
{
    use Timestampable;
}

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

  • ใช้ trait แทน inheritance เพราะ “สะดวกกว่า” — trait ไม่ให้ type ($x instanceof SomeTrait ไม่มี) ถ้าต้อง type hint ต้องมี interface คู่
  • trait เยอะเกินในคลาสเดียว จนไม่รู้ว่าเมธอดมาจากไหน — ถ้าเกิน 2–3 อัน อาจเป็นสัญญาณว่าคลาสทำหน้าที่เยอะไป
  • trait ที่มี state (property) แชร์กัน — property ของ trait เป็นของ แต่ละอ็อบเจกต์ ไม่ได้แชร์ข้ามอ็อบเจกต์ (เว้นแต่เป็น static)
  • static property ใน trait — แต่ละคลาสที่ใช้ trait ได้ตัวแปร static แยกกัน (ไม่ใช่ตัวเดียวกันทั้งหมด)
  • ชื่อเมธอด trait ชนกันแล้วไม่ resolve — PHP fatal error ทันที ต้องใช้บล็อก { ... insteadof ... }
  • คาดหวังว่า trait จะเรียก constructor ให้ — trait ไม่มี __construct ที่รันอัตโนมัติ ต้องเรียกเมธอด init เองจาก constructor ของคลาส

สรุป

  • trait = ชุดเมธอด/property พร้อม body เอาไป use ในคลาสไหนก็ได้ เหมือนก็อปโค้ดแต่อยู่ที่เดียว
  • ใช้หลาย trait ได้ ชนกันแก้ด้วย insteadof / as
  • abstract ใน trait บังคับให้คลาสที่ใช้ต้องมีเมธอดนั้น
  • ลำดับ override: คลาสเอง > trait > แม่
  • trait ไม่ให้ type — คู่กับ interface เมื่อต้องการ type hint

บทถัดไปว่าด้วย static property/method, class constant, self:: vs static:: (late static binding) และ ::class