Article

Property Hooks in PHP 8.4 — A Game Changer

PHP 8.4 introduces property hooks, one of the most significant additions to the language in years. Property hooks allow you to define get and set behaviors directly on class properties, eliminating the need for boilerplate getter/setter methods.

Here is a simple example:

class User {
    public string $name {
        set(string $value) {
            $this->name = trim($value);
        }
    }
}

This feature, combined with asymmetric visibility (public private(set)), makes PHP classes significantly more expressive and concise.

Tags: PHP XMF XOOPS

Comments

Admin March 1, 2025

Property hooks are indeed a game changer. I have been waiting for this feature since PHP 7. The ability to define get/set right on the property is so much cleaner than separate methods.
Reply

PHPDev42 March 2, 2025

Great article! How does this interact with asymmetric visibility? Can you have a public getter but a private setter using both features together?
Reply

Admin March 3, 2025

Yes, you can combine them. For example: public private(set) string $name { get => strtoupper($this->name); } gives you a public readable property with a private setter and a custom get hook.
Reply