PHP magic methods
magic method คือเมธอดที่ PHP เรียกให้เองอัตโนมัติ เมื่อเกิดเหตุการณ์บางอย่างกับอ็อบเจกต์ ชื่อขึ้นต้นด้วย __ (double underscore) เราเจอ __construct มาแล้ว บทนี้ดูตัวที่เหลือ
__toString — อ็อบเจกต์เป็นสตริง
ถูกเรียกเมื่ออ็อบเจกต์ถูกใช้ในบริบทที่ต้องการสตริง (echo, ต่อสตริง, (string)):
<?php
declare(strict_types=1);
class Money
{
public function __construct(
public int $satang,
public string $currency = 'THB',
) {}
public function __toString(): string
{
return number_format($this->satang / 100, 2) . ' ' . $this->currency;
}
}
$price = new Money(59900);
echo "ราคา: $price\n"; // ราคา: 599.00 THB
echo (string) $price, "\n"; // 599.00 THBคลาสที่มี __toString() จะนับเป็น Stringable อัตโนมัติ — type hint Stringable|string ได้
__invoke — เรียกอ็อบเจกต์เหมือนฟังก์ชัน
<?php
class Multiplier
{
public function __construct(private int $factor) {}
public function __invoke(int $n): int
{
return $n * $this->factor;
}
}
$triple = new Multiplier(3);
echo $triple(10), "\n"; // 30 — เรียกอ็อบเจกต์ตรง ๆ
// ใช้แทน closure ได้ทุกที่
$nums = array_map($triple, [1, 2, 3]); // [3, 6, 9]
var_dump(is_callable($triple)); // trueเหมาะกับ “อ็อบเจกต์ที่มีหน้าที่เดียว” เช่น validator, formatter, handler
__get / __set — ดักการเข้าถึง property ที่ไม่มี
ถูกเรียกเมื่ออ่าน/เขียน property ที่ ไม่มีอยู่จริง หรือเข้าถึงไม่ได้:
<?php
class Config
{
private array $data = [];
public function __get(string $name): mixed
{
return $this->data[$name] ?? null;
}
public function __set(string $name, mixed $value): void
{
$this->data[$name] = $value;
}
public function __isset(string $name): bool
{
return isset($this->data[$name]);
}
public function __unset(string $name): void
{
unset($this->data[$name]);
}
}
$config = new Config();
$config->timeout = 30; // เรียก __set('timeout', 30)
echo $config->timeout, "\n"; // เรียก __get('timeout') -> 30
var_dump(isset($config->timeout)); // เรียก __isset -> trueระวัง: วิธีนี้ทำให้ IDE ไม่รู้จัก property เหล่านี้ (ไม่มี autocomplete, ไม่เตือนพิมพ์ผิด) และ PHPStan วิเคราะห์ไม่ได้ ใช้เฉพาะเมื่อจำเป็นจริง ๆ (เช่น wrapper ของข้อมูล dynamic) — งานทั่วไปประกาศ property ตรง ๆ ดีกว่า
__call / __callStatic — ดักการเรียกเมธอดที่ไม่มี
<?php
class QueryBuilder
{
private array $wheres = [];
public function __call(string $method, array $args): static
{
if (str_starts_with($method, 'where')) {
$column = lcfirst(substr($method, 5)); // whereStatus -> status
$this->wheres[$column] = $args[0];
return $this;
}
throw new BadMethodCallException("ไม่รู้จักเมธอด $method");
}
public function toSql(): string
{
$conditions = [];
foreach ($this->wheres as $col => $val) {
$conditions[] = "$col = " . var_export($val, true);
}
return 'WHERE ' . implode(' AND ', $conditions);
}
}
$sql = (new QueryBuilder())
->whereStatus('active')
->whereRole('admin')
->toSql();
echo $sql, "\n"; // WHERE status = 'active' AND role = 'admin'__callStatic ทำแบบเดียวกันสำหรับ Class::method() ที่ไม่มี
__clone — ปรับแต่งตอน clone
clone ทำ shallow copy — property ที่เป็นอ็อบเจกต์ยังชี้ตัวเดิม __clone() ให้แก้ตรงนั้น:
<?php
class Invoice
{
public function __construct(
public string $number,
public DateTimeImmutable $date,
public array $lines = [],
) {}
public function __clone(): void
{
// สร้าง number ใหม่เมื่อ clone
$this->number = $this->number . '-COPY';
// DateTimeImmutable ไม่ต้อง clone (immutable อยู่แล้ว)
}
}
$original = new Invoice('INV-001', new DateTimeImmutable());
$copy = clone $original;
echo $copy->number, "\n"; // INV-001-COPY__destruct — ตอนอ็อบเจกต์ถูกทำลาย
ถูกเรียกเมื่อไม่มีตัวแปรอ้างถึงอ็อบเจกต์แล้ว (หรือจบสคริปต์) เหมาะกับการปิด resource:
<?php
class TempFile
{
private string $path;
public function __construct()
{
$this->path = tempnam(sys_get_temp_dir(), 'tmp');
}
public function write(string $data): void
{
file_put_contents($this->path, $data);
}
public function __destruct()
{
if (is_file($this->path)) {
unlink($this->path); // ลบไฟล์ชั่วคราวทิ้ง
}
}
}รายการ magic method ทั้งหมด
| เมธอด | ถูกเรียกเมื่อ |
|---|---|
__construct / __destruct | สร้าง / ทำลายอ็อบเจกต์ |
__get / __set / __isset / __unset | เข้าถึง property ที่ไม่มี/เข้าไม่ถึง |
__call / __callStatic | เรียกเมธอดที่ไม่มี |
__toString | ใช้อ็อบเจกต์เป็นสตริง |
__invoke | เรียกอ็อบเจกต์เป็นฟังก์ชัน |
__clone | หลัง clone |
__serialize / __unserialize | serialize() / unserialize() |
__debugInfo | var_dump() |
เรื่องที่คนมักพลาด
- ใช้
__get/__setกับทุกคลาสเพื่อความ “ยืดหยุ่น” — เสีย autocomplete, เสียการตรวจ type, ดีบั๊กยาก ประกาศ property ตรง ๆ เป็นค่าเริ่มต้น __toStringโยน exception — ก่อน PHP 7.4 ทำไม่ได้เลย, ตอนนี้ทำได้แต่เสี่ยงเพราะechoกลางที่ไหนก็ระเบิดได้ ควรคืนสตริงเสมอ- ลืมว่า
__getถูกเรียกเฉพาะ property ที่เข้าไม่ถึง — ถ้ามี public property ชื่อเดียวกัน__getจะไม่ทำงาน - พึ่ง
__destructเป็นกลไกหลักในการปิด resource — ลำดับการเรียกตอนจบสคริปต์ไม่แน่นอน ปิด resource แบบ explicit ดีกว่า (เช่นเมธอดclose()) __callกลืน typo — เรียกเมธอดพิมพ์ผิดแล้วไปเข้า__callแทนที่จะ error ให้throwในกรณีที่ไม่รู้จักcloneอ็อบเจกต์ที่มี property เป็นอ็อบเจกต์ mutable โดยไม่มี__clone— สองอ็อบเจกต์แชร์ตัวลูกกัน แก้ตัวหนึ่งกระทบอีกตัว
สรุป
- magic method = เมธอด
__xxxที่ PHP เรียกอัตโนมัติในสถานการณ์เฉพาะ - ใช้บ่อยและปลอดภัย:
__construct,__toString,__invoke,__clone,__destruct - ใช้อย่างระวัง:
__get/__set/__call— ทำให้ IDE และเครื่องมือวิเคราะห์ช่วยไม่ได้ - ถ้าไม่จำเป็นจริง ๆ ประกาศ property และเมธอดตรง ๆ เสมอ
จบเฟส OOP บทถัดไปเข้าเฟส 4 เริ่มที่ exception — วิธีจัดการข้อผิดพลาดแบบที่ควบคุมได้ ด้วย try/catch/finally และ exception ที่เขียนเอง