Property Hook
Property hooks are a feature of PHP 8.4, where accessors can be defined with the property.
Hooks are for set and get: they allow extra commands to be always executed at setting or getting time of a property.
Hooks look like the magic methods __set and __get, with a few differences: they are dedicated to a property, and easier to write.
Property hooks are also called Property Accessors, in other languages.
<?php
class Elephpant {
public string $trunkLength {
// this is the single line definition of a hook
// the expression is the returned value
get => $this->trunkLength . '1';
set {
// $value is the unique parameter of that function
$this->trunkLength = $value;
}
}
}
?>
See Also
- PHP 8.4 Property Hooks
- PHP 8.4 Property Hooks: The Ultimate Guide for Developers
- PHP RFC: Property hook improvements
- A Guide to PHP 8.4 Property Hooks
- PHP’s New Property Hooks Are Here—But Should You Use Them?
- Using property hooks in PHP