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!

