PHP 8.4 Property Hooks: The Ultimate Guide for Developers
PHP 8.4, coming in November 2024, introduces a new feature called property hooks. This feature makes it easier to work with class properties by allowing you to define custom behavior when getting or setting property values.
In this article, we'll explain what property hooks are, how they work, and provide simple examples to help you understand how to use them.
What Are PHP Property Hooks?
Property hooks let you add custom logic directly to class properties. This means you can interact with properties like $person->name
without needing separate methods like $person->getName()
or $person->setName()
.
If you’ve used Laravel before, you might recognize that property hooks are similar to Laravel’s accessors and mutators, which also allow you to control how data is accessed and modified.
The "get" Hook
The get
hook is used to control what happens when you access a property. For example, let's say you have a Person
class, and you want to ensure that whenever you access the fullName
property, it returns the first name and last name combined:
class Person
{
public string $fullName {
get {
return $this->firstName . ' ' . $this->lastName;
}
}
public function __construct(
public string $firstName,
public string $lastName
) {}
}
$person = new Person('John', 'Doe');
echo $person->fullName; // John Doe
In this example, when you access $person->fullName
, the get
hook combines firstName
and lastName
and returns "John Doe".
Type Compatibility
The type of the value returned by the get
hook must match the type declared for the property. If the types don’t match, PHP will try to convert the value automatically unless strict types are enabled. If strict types are enabled, you need to ensure that the returned value exactly matches the property’s type, or an error will occur.
The "set" Hook
The set
hook is used to control what happens when you assign a value to a property. For example, let’s say you want to ensure that any name assigned to a Person
class is stored in uppercase:
class Person
{
public string $name {
set(string $value) {
$this->name = strtoupper($value);
}
}
public function __construct(string $name)
{
$this->name = $name;
}
}
$person = new Person('john');
echo $person->name; // JOHN
In this example, when you set $person->name
to "john", the set
hook automatically converts it to "JOHN" before storing it.
Type Compatibility
Similar to the get
hook, the type of the value passed to the set
hook must be compatible with the property’s type. If the types don’t match, PHP will raise an error if strict types are enabled.
Using "get" and "set" Hooks Together
You can use both get
and set
hooks on the same property to control how it is accessed and modified. For example, let’s create a Person
class where the fullName
property automatically splits a full name into first and last names when it’s set, and combines them when it’s accessed:
class Person
{
public string $fullName {
get {
return $this->firstName . ' ' . $this->lastName;
}
set(string $value) {
[$this->firstName, $this->lastName] = explode(' ', $value);
}
}
private string $firstName;
private string $lastName;
public function __construct(string $fullName)
{
$this->fullName = $fullName;
}
}
$person = new Person('John Doe');
echo $person->fullName; // John Doe
$person->fullName = 'Jane Smith';
echo $person->fullName; // Jane Smith
In this example, when you set $person->fullName
to "Jane Smith", the set
hook splits the name into firstName
and lastName
. When you access $person->fullName
, the get
hook combines these parts and returns "Jane Smith".
Write-only and Read-only Properties
With property hooks, you can create write-only or read-only properties.
Write-only: You can only assign a value but not read it. This happens when you define a
set
hook but noget
hook.Read-only: You can only read the value but not assign it. This happens when you define a
get
hook but noset
hook.
Write-only Example
Here’s an example where you can only set a password but not read it:
class User
{
public string $password {
set(string $value) {
$this->hashedPassword = password_hash($value, PASSWORD_DEFAULT);
}
}
private string $hashedPassword;
}
$user = new User();
$user->password = 'secret';
// echo $user->password; // Error: Cannot access write-only property
Read-only Example
Here’s an example where you can only read a calculated value but not set it directly:
class Circle
{
public float $radius;
public float $area {
get {
return pi() * $this->radius ** 2;
}
}
public function __construct(float $radius)
{
$this->radius = $radius;
}
}
$circle = new Circle(5);
echo $circle->area; // 78.5398...
// $circle->area = 100; // Error: Cannot set read-only property
Things to Keep in Mind When Using Property Hooks
When working with property hooks in PHP, there are several important points to consider:
Object Properties Only: Property hooks can only be applied to object properties, not static properties. This means that if a property is static, it cannot have a hook.
Override Behavior: Property hooks will override any default behavior for reading or writing to a property. This means the custom logic in the hooks will control how the property is accessed or modified.
Access to Methods and Properties: Property hooks can access all the object’s methods and properties, whether they are public, private, or protected. This includes properties that might have their own hooks.
No References Allowed: You cannot set references on hooked properties. This is because modifying a value by reference would bypass any
set
hook that is defined for the property.Inheritance and Hook Redefinition: In a child class, you can redefine individual hooks for a property by redefining the property and only the hooks you want to change. The type and visibility of the property follow their own rules, and each hook can independently override the parent class’s implementation.
Conclusion
Property hooks in PHP 8.4 make working with class properties easier and more flexible. By allowing you to control how properties are accessed and modified directly within the property definition, you can write cleaner and more intuitive code. Whether you're creating simple classes or more complex logic, property hooks are a powerful tool in your PHP toolkit.
Read more about property hooks in the RFC here.
.
🔥 Supercharge Your Development with Ctrl+Alt+Cheat
I’m super excited to introduce Ctrl+Alt+Cheat, the ultimate cheat sheet extension for VSCode.
👉 Download Ctrl+Alt+Cheat today and start coding like a pro!
Please login or create new account to add your comment.