PHP Reference ยท Functions and Classes
Property hooks (PHP 8.4)
Reference for PHP 8.4 property hooks: get and set hooks, short syntax, virtual properties, validation, interfaces, inheritance and current limits.
Property hooks, added in PHP 8.4, attach code directly to a property. A get hook runs when the property is read and a set hook runs when it is written, so you can validate, normalize or compute values without writing separate getter and setter methods. Callers keep using plain $object->name syntax.
A property with hooks is either backed (it stores a value and your hooks wrap that storage) or virtual (no storage; the value is computed in get). Code can start with a plain property and add hooks later without changing any caller.
class User { public string $name { set => trim($value); } }
Try it
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.
Syntax
public Type $name { get { return ...; } // block form set(Type $value) { ... } // optional parameter, defaults to the property type } public Type $name { get => expression; set => expression; } // short form
- In
set, the short formset => expr;stores the result ofexprin the backing value. The block form must assign to$this->nameitself. - Inside a hook,
$this->namereads or writes the backing storage directly and does not call the hook again. - The parameter of
setmay have a wider type than the property (for examplestring|Stringable); the assigned value is still checked against the property type afterwards.
Usage notes
- Virtual properties have a
gethook (and optionallyset) and never read or write$this->nameinside them. They take no memory and appear without a default value. - A property that only defines
getand is virtual is read-only: writing throws anError. - Backed properties still need to be initialized (constructor or default) before they are read, as with any typed property.
- Interfaces can require hooked properties:
public string $name { get; }means implementers must provide at least a readable$name. - Inheritance. A child may override hooks. Call the parent's hook with
parent::$name::get()orparent::$name::set($value). - Not allowed: hooks on
staticproperties and onreadonlyproperties. Constructor-promoted properties can have hooks, written right after the parameter. - Not magic methods. Hooks are checked by the compiler and are faster and more explicit than
__getand__set; they do not cover undeclared properties. - Reflection and
var_dumpstill show hooked properties; useReflectionProperty::getHooks()to inspect hooks.