PHP 8.4 Property Hooks
PHP 8.4 introduces property hooks, a powerful feature that allows you to add custom logic when getting or setting properties.
Basic Example
class User
{
public string $name {
get => strtoupper($this->name);
set => ucfirst($value);
}
}
$user = new User();
$user->name = 'john doe';
echo $user->name; // Output: JOHN DOE
Computed Properties
Create virtual properties without backing storage:
class Rectangle
{
public function __construct(
public float $width,
public float $height
) {}
public float $area {
get => $this->width * $this->height;
}
}
Validation in Setters
class Product
{
private float $_price;
public float $price {
get => $this->_price;
set {
if ($value < 0) {
throw new InvalidArgumentException('Price must be positive');
}
$this->_price = $value;
}
}
}
Benefits
- ✅ Cleaner than
__get()and__set()magic methods - ✅ Better IDE support and static analysis
- ✅ More explicit and readable code
- ✅ Type-safe property access
Property hooks make PHP objects more powerful while maintaining backward compatibility!
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í.
Đề bài
Add a computed `fahrenheit` property to the Temperature class using a PHP 8.4 property hook, so that reading $t->fahrenheit returns the Celsius value converted to Fahrenheit (F = C × 9/5 + 32) — no method call and no stored field.
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

