PHP static, class constant และ ::class



ปกติ property/method ผูกกับ อ็อบเจกต์ (ต้อง new ก่อน) แต่ static ทำให้ผูกกับ คลาส เรียกได้โดยไม่ต้องสร้างอ็อบเจกต์

class constant

ค่าคงที่ประจำคลาส ประกาศด้วย const เข้าถึงด้วย :::

<?php
declare(strict_types=1);

class HttpResponse
{
    const int OK = 200;
    const int NOT_FOUND = 404;
    const string DEFAULT_CONTENT_TYPE = 'application/json';

    public function __construct(
        public int $status = self::OK,
    ) {}
}

echo HttpResponse::NOT_FOUND, "\n";              // 404
echo HttpResponse::DEFAULT_CONTENT_TYPE, "\n";   // application/json

$res = new HttpResponse();
echo $res->status, "\n";                          // 200
  • ในคลาสอ้างด้วย self::OK, นอกคลาสอ้างด้วย HttpResponse::OK
  • constant มี visibility ได้ (private const, protected const)
  • PHP 8.3 ใส่ type ให้ constant ได้: const int OK = 200;
  • ตั้งชื่อ UPPER_SNAKE_CASE

ถ้าค่าคงที่หลายตัวเป็นชุดเดียวกัน (เช่น สถานะออเดอร์) ใช้ enum (บทหน้า) แทน — ได้ type safety มากกว่า

static property

ตัวแปรที่ แชร์กันทุกอ็อบเจกต์ของคลาสนั้น มีชุดเดียว:

<?php
class Counter
{
    private static int $count = 0;

    public function __construct()
    {
        self::$count++;
    }

    public static function total(): int
    {
        return self::$count;
    }
}

new Counter();
new Counter();
new Counter();

echo Counter::total(), "\n";     // 3

self::$count (มี $) เข้าถึง static property, ต่างจาก self::OK (ไม่มี $) ที่เป็น constant

ใช้ static property ด้วยความระวัง — มันคือ global state แบบซ่อน ทำให้เทสต์ยาก (ค่าค้างข้ามเทสต์) ส่วนใหญ่มีทางออกแบบอื่นที่ดีกว่า

static method

เมธอดที่เรียกได้โดยไม่ต้องมีอ็อบเจกต์ ไม่มี $this:

<?php
class Money
{
    private function __construct(
        public readonly int $satang,
    ) {}

    public static function fromBaht(float $baht): self
    {
        return new self((int) round($baht * 100));
    }

    public static function zero(): self
    {
        return new self(0);
    }

    public function toBaht(): float
    {
        return $this->satang / 100;
    }
}

$price = Money::fromBaht(59.90);
echo $price->satang, "\n";        // 5990
echo $price->toBaht(), "\n";      // 59.9

รูปแบบนี้เรียกว่า named constructor / factory method — __construct เป็น private แล้วให้สร้างผ่าน static method ที่ชื่อสื่อความหมาย (fromBaht, zero) และ validate ได้

self:: กับ static:: — late static binding

ต่างกันเมื่อมีการสืบทอด:

  • self:: — อ้างถึงคลาสที่ เขียนโค้ดบรรทัดนั้น (fixed ตอน compile)
  • static:: — อ้างถึงคลาสที่ ถูกเรียกจริง ตอน runtime (late binding)
<?php
declare(strict_types=1);

class Model
{
    public static function create(): static
    {
        return new static();      // static = คลาสที่เรียกจริง
    }

    public function whoAmI(): string
    {
        return static::class;
    }
}

class UserModel extends Model {}
class ProductModel extends Model {}

$u = UserModel::create();
echo $u->whoAmI(), "\n";          // UserModel  (ไม่ใช่ Model!)
echo get_class(ProductModel::create()), "\n";   // ProductModel

ถ้าเขียน new self() แทน new static() จะได้ Model เสมอ — static คือสิ่งที่ทำให้ factory method ในคลาสแม่สร้างอ็อบเจกต์ของคลาสลูกที่ถูกต้อง

::class — ชื่อคลาสแบบปลอดภัย

<?php
echo Money::class, "\n";              // App\Money  (ชื่อเต็มพร้อม namespace)

$obj = new Money(100);
echo $obj::class, "\n";               // App\Money  (PHP 8.0+)

ใช้ SomeClass::class แทนการเขียนสตริง 'App\Money' ตรง ๆ เพราะ:

  • IDE ตามได้ / rename ได้
  • ผิดแล้วรู้ทันที (คลาสไม่มี = error) ต่างจากสตริงที่พิมพ์ผิดก็เงียบ
  • ใช้กับ namespace ได้ถูกต้องเสมอ

เจอบ่อยใน type check, error message, และ DI container:

<?php
$container->bind(PaymentGateway::class, StripeGateway::class);
match ($e::class) {
    NotFoundException::class => http_response_code(404),
    ValidationException::class => http_response_code(422),
};

static ใน closure / arrow function

<?php
$fn = static fn($x) => $x * 2;    // static = ไม่ผูก $this ประหยัดหน่วยความจำเล็กน้อย

ใส่ static หน้า closure ถ้าข้างในไม่ได้ใช้ $this — เป็นนิสัยที่ดีในเมธอดของคลาส

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

  • สับสน self::CONST (ไม่มี $) กับ self::$prop (มี $) — constant ไม่มี $, static property มี
  • ใช้ $this ใน static method — ไม่มี $this จะ error
  • new self() ใน factory method ของคลาสแม่ แล้วสงสัยทำไมคลาสลูกได้อ็อบเจกต์ผิดชนิด — ใช้ new static()
  • static property เป็นที่เก็บ state ของแอป — ค่าค้างข้ามคำขอไม่ได้ (PHP เริ่มใหม่ทุก request) และค้างข้ามเทสต์ได้ (ปัญหา) หลีกเลี่ยง
  • เขียนชื่อคลาสเป็นสตริง 'Money' แทน Money::class — พอมี namespace จะพัง และ refactor ยาก
  • class constant กับอาร์เรย์ที่ต้องคำนวณ — constant ต้องเป็น expression ที่ประเมินตอน compile ได้ (ค่าคงที่, constant อื่น, การต่อสตริง) เรียกฟังก์ชันไม่ได้

สรุป

  • const = ค่าคงที่ประจำคลาส เข้าถึงด้วย Class::NAME / self::NAME (ไม่มี $)
  • static property/method ผูกกับคลาส ไม่ต้อง new — static property คือ shared state ใช้อย่างระวัง
  • factory method (static method ที่คืน self/static) + private __construct = named constructor ที่ validate ได้
  • self:: = คลาสที่เขียนโค้ด, static:: = คลาสที่เรียกจริง (ใช้ new static() ใน factory ของคลาสแม่)
  • Class::class ให้ชื่อคลาสเต็มแบบที่ IDE/PHP ตรวจสอบได้ — ใช้แทนสตริงเสมอ

บทถัดไปว่าด้วย enum — ชุดค่าที่กำหนดไว้ตายตัว ซึ่งเป็นทางเลือกที่ปลอดภัยกว่า class constant เมื่อค่าเป็นชุดเดียวกัน