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.
<?php
class X
{
public string $property {
// this is the single line definition of a hook
// the expression is the returned value
get => $this->property . _1;
set {
// $value is the unique parameter of that function
$this->property = $value;
}
}
}
?>
See also PHP 8.4 Property Hooks, PHP 8.4 Property Hooks: The Ultimate Guide for Developers, PHP RFC: Property hook improvements
Related : Properties, __get() Method, __set() Method, Magic Methods