PHP

PHP 8.4 Property Hooks

With PHP 8.4 due to be released in a few months, let’s take a look at one of the more interesting new features – property hooks.

PHP 8.4 is set to be released in November 2024, there are a few parts of this release that I am actually excited about. One of these is property hooks.

A number of languages natively have property hooks, which are designed to avoid copious lines of effectively repeated, or sometimes downright ugly, code. Here’s an example in C#, where you can see a getter and setter created with an extremely minimal amount of code.

private string _Name;

public string Name
{
get { return _Name; }
set { _Name = value; }
}

In the past (or if you’re reading this before PHP 8.4 is released, now) you’d create getters and setters much like with the methods in below User class. Not too bad, right? But what if your class has five properties? 10 or even 50 properties? It just gets to be a repetitive mess in there.

class User 
{
public function __construct(private string $name)
{}

public function getName(): string {
return $this->name;
}

public function setName(string $name): void {
$this->name = $name;
}
}

So we could avoid this with a switch statement or similar in __get or __set methods but the problem there is it becomes hard to reason with. These magic methods then become extremely large and unwieldy beasts when we should be striving for simplicity.

Enter property hooks. In a nutshell, all we do is write the following property definition:

class User
{
public function __construct(private string $name)
{}

public string $name {
get => $this->name;
set => $value;
}
}

Admittedly, this is only really syntactic sugar for __get and __set, however it can significantly reduce the amount of code and cognitive load you’d otherwise have to grapple with.

Succinct, more readable code can only ever be a good thing.

For more info, see the RFC detail at https://wiki.php.net/rfc/property-hooks.