PHP 8.4: Property Hooks

spO0q 🐒 - Jun 6 - - Dev Community

PHP 8.4 is expected for this fall. Let's review the RFC "Property Hooks."

Disclaimer (08/06)

After reading a comment on this post, I think it should be indicated that the idea with this RFC is not to use it for anything and everything.

It's not meant to replace all cases, but can be very beneficial in case you need it (e.g., data object).

What are PHP RFCs?

RFC means "Request For Comments." It's a pretty old concept (probably older than Internet itself) many core teams and their community use to discuss and implement new features, deprecate obsolete code or enhance existing structures.

The process for PHP is pretty well-documented, so do not hesitate to read this page if you want more details.

Here we'll focus on a specific RFC that looks promising: Property Hooks.

Other notable RFCs

While we'll focus on Property Hooks, there are other RFCs you might want to read:

Where to find all accepted RFCs?

You can check this page.

Property hooks in short

This RFC aims to remove the hassle of using boilerplate (e.g., getters/setters) for common interaction with object's properties.

PHP 8.0 already allows promoting properties in the constructor, so it's far less verbose than it used to be:

class User 
{
    public function __construct(public string $name) {}
}
Enter fullscreen mode Exit fullscreen mode

However, the RFC underlines the fact there's no built-in way to add custom behaviors or validation to these properties, which ultimately brings developers back to clumsy and verbose solutions (boilerplate or magic getters/setters).

With property hooks, this could be built-in the language:

interface Named
{
    public string $fullName { get; } // make the hook required
}

class User implements Named
{
    public function __construct(private string $firstName, private string $lastName) {}

    public string $fullName {
        get => strtoupper($this->firstName) . " " . strtoupper($this->lastName);
    }
}
Enter fullscreen mode Exit fullscreen mode

What's the problem with getters and setters?

You may read this [old] introduction:

👉🏻 When used blindly, setters and getters can break encapsulation, as the idea is to prevent anybody from modifying the object from the outside, and you probably want to keep the implementation private.

Wrap up

PHP contributors seem more and more inspired by other languages (e.g. Kotlin).

The RFC only includes two hooks: set and get, but there could be more hooks in the future.

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .