Medium PHP

PHP 8.4 Property Hooks Explained

Discover the new property hooks feature in PHP 8.4 that provides a cleaner way to add logic to property access.

21 Jun, 2026 1 min 11 Views 3 Code blocks

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!

Interactive challenge

Try the challenge

Practice what you just learned. Write your solution, reveal hints if you get stuck.

Instructions

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.

LanguagePHP

Starter code

php
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

Your solution

Solution · php
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