一個只有兩個屬性的類別,為了在設定時去空白、檢查負數,就要寫四個方法:
class Product {
private string $name;
private int $price;
public function getName(): string { return $this->name; }
public function setName(string $name): void { $this->name = trim($name); }
public function getPrice(): int { return $this->price; }
public function setPrice(int $price): void {
if ($price price = $price;
}
}
PHP 8.4 的 property hooks 讓這些邏輯直接寫在屬性上。
用 hooks 改寫
class Product {
public string $name {
set => trim($value);
}
public int $price {
set {
if ($value price = $value;
}
}
// 虛擬屬性:沒有自己的儲存空間,每次讀取時計算
public int $priceWithTax {
get => (int) round($this->price * 1.05);
}
public function __construct(string $name, int $price) {
$this->name = $name;
$this->price = $price;
}
}
使用時就是一般的屬性存取:
$p = new Product(' Keyboard ', 1200);
var_dump($p->name, $p->price, $p->priceWithTax);
$p->price = 1500;
var_dump($p->priceWithTax);
$p->price = -1;
$p->priceWithTax = 1;
PHP 8.5.4 的輸出:
string(8) "Keyboard"
int(1200)
int(1260)
int(1575)
InvalidArgumentException: 價格不能是負數
Error: Property Product::$priceWithTax is read-only
set => 運算式:運算式的結果就是存進去的值,$value是外部傳入的值。set { ... }:區塊寫法,要自己寫$this->price = $value。- 只有
get的屬性沒有實際儲存空間,外部寫入會丟出 Error。
構造函式裡的 $this->name = $name 也會經過 set hook,所以名稱一樣被去掉空白。
private(set):外部唯讀,內部可改
很多屬性只需要「外面能讀、只有自己能改」,PHP 8.4 的非對稱可見性一行就能表達:
class Order {
public private(set) string $status = 'pending';
public private(set) array $items = [];
public function add(string $item): void { $this->items[] = $item; }
public function ship(): void { $this->status = 'shipped'; }
}
$o = new Order();
$o->add('book');
$o->ship();
echo $o->status, ' ', count($o->items); // shipped 1
$o->status = 'cancelled';
$o->items[] = 'hack';
Error: Cannot modify private(set) property Order::$status from global scope
Error: Cannot indirectly modify private(set) property Order::$items from global scope
陣列的 $o->items[] = ... 也被擋下,外部只能透過 add() 新增。
也可以寫在構造函式的屬性提升裡:
final class Money {
public function __construct(public private(set) int $amount) {}
}
介面可以要求屬性
interface HasLabel {
public string $label { get; }
}
class Tag implements HasLabel {
public function __construct(private string $name) {}
public string $label { get => '#' . $this->name; }
}
echo (new Tag('php'))->label; // #php
過去介面只能定義方法,現在可以要求「一定要有可讀的 label 屬性」,實作方式由類別自己決定。
陷阱:有 set hook 的陣列不能直接附加
class Cart {
public array $items = [] {
set => array_values($value);
}
}
$c = new Cart();
$c->items[] = 'x';
Error: Indirect modification of Cart::$items is not allowed
$c->items[] = 'x' 是直接修改陣列內容,不會經過 set hook,PHP 乾脆禁止。要整個重新指定:$c->items = [...$c->items, 'x'];,或像上面的 Order 一樣提供 add() 方法。
什麼時候用
- 設定時要驗證或整理資料,例如去空白、檢查範圍。
- 由其他屬性算出來的值,用只有
get的虛擬屬性。 - 外部只能讀的狀態,用
private(set),不必再寫 getter。
邏輯複雜、會呼叫資料庫或外部服務的,仍然寫成方法比較清楚,讀程式的人看到 $obj->x 不會預期背後有昂貴的操作。
發表留言