PHP 8.4 Property Hooks
PHP 8.4 ra mắt property hooks, tính năng xịn sò cho phép nhét thêm logic tùy chỉnh ngay lúc get hoặc set property.
Ví dụ cơ bản
class User
{
public string $name {
get => strtoupper($this->name);
set => ucfirst($value);
}
}
$user = new User();
$user->name = 'john doe';
echo $user->name; // Kết quả: JOHN DOE
Computed Properties
Tạo property ảo, không cần chỗ lưu trữ riêng:
class Rectangle
{
public function __construct(
public float $width,
public float $height
) {}
public float $area {
get => $this->width * $this->height;
}
}
Validate ngay trong setter
class Product
{
private float $_price;
public float $price {
get => $this->_price;
set {
if ($value < 0) {
throw new InvalidArgumentException('Giá phải là số dương');
}
$this->_price = $value;
}
}
}
Được cái gì
- ✅ Gọn hơn nhiều so với magic method
__get()và__set() - ✅ IDE support với static analysis ngon hơn hẳn
- ✅ Code rõ ràng, dễ đọc hơn
- ✅ Truy cập property mà vẫn type-safe
Property hooks giúp object PHP mạnh mẽ hơn mà vẫn giữ được tương thích ngược!
Thử thách
Luyện tập ngay điều vừa học. Viết lời giải, mở gợi ý nếu bí.
Code khởi tạo
class Temperature
{
public function __construct(public float $celsius) {}
// TODO: add a virtual `fahrenheit` property using a get hook
}
$t = new Temperature(25);
echo $t->fahrenheit; // expected: 77
Lời giải của bạn
class Temperature
{
public function __construct(public float $celsius) {}
public float $fahrenheit {
get => $this->celsius * 9 / 5 + 32;
}
}
$t = new Temperature(25);
echo $t->fahrenheit; // 77

