Property hooks

suggest change

PHP 8.4 added property hooks: code that runs when a property is read (get) or written (set). Callers keep using plain property syntax like $user->email = '...', while the class validates, normalizes or computes the value behind the scenes.

Before 8.4 you had two options. You could expose a public property and give up control, or you could write getEmail()/setEmail() methods "just in case". Hooks let you start with a public property and add logic later without changing any caller.

This article covers:

All examples need PHP 8.4 or newer.

Related topics: Properties, Immutability, Composition and delegation, Interfaces, Abstract Classes and Magic Methods.

A first set hook

You declare a hook in a { ... } block after the property name:

<?php
class User
{
    public string $email {
        set {
            if (!str_contains($value, '@')) {
                throw new InvalidArgumentException("Invalid email: $value");
            }
            $this->email = strtolower($value);
        }
    }

    public function __construct(string $email)
    {
        $this->email = $email;
    }
}

$u = new User('Ada@Example.COM');
echo $u->email, "\n";

$u->email = 'Grace@Example.com';
echo $u->email, "\n";

try {
    $u->email = 'not-an-email';
} catch (InvalidArgumentException $e) {
    echo $e->getMessage(), "\n";
}
echo $u->email, "\n";

Output:

ada@example.com
grace@example.com
Invalid email: not-an-email
grace@example.com

There's no get hook here, so reads return the stored value as usual.

get hooks: short and block form

A get hook computes the value returned on a read. If the body is a single expression, use the short => form. Otherwise use a block with return:

<?php
class Person
{
    public function __construct(
        public string $first,
        public string $last,
    ) {}

    // short form: an expression
    public string $fullName {
        get => "$this->first $this->last";
    }

    // block form: statements, must return
    public string $initials {
        get {
            $f = substr($this->first, 0, 1);
            $l = substr($this->last, 0, 1);
            return strtoupper($f . $l);
        }
    }
}

$p = new Person('Ada', 'Lovelace');
echo $p->fullName, "\n";
echo $p->initials, "\n";

$p->last = 'Byron';
echo $p->fullName, "\n";

Output:

Ada Lovelace
AL
Ada Byron

$fullName is recomputed on every read, so it always reflects the current $first and $last. The return value is checked against the declared type (string) just like a function's return type.

Virtual and backed properties

PHP decides whether a hooked property gets its own storage by looking at the hook bodies:

A virtual property with only a get hook is read-only:

<?php
class Rectangle
{
    public function __construct(
        public float $width,
        public float $height,
    ) {}

    public float $area {
        get => $this->width * $this->height;
    }
}

$r = new Rectangle(3, 4);
echo $r->area, "\n";

try {
    $r->area = 20;
} catch (Error $e) {
    echo get_class($e), ': ', $e->getMessage(), "\n";
}

var_dump($r);
print_r(get_object_vars($r));
var_dump(isset($r->area));

Output:

12
Error: Property Rectangle::$area is read-only
object(Rectangle)#1 (2) {
  ["width"]=>
  float(3)
  ["height"]=>
  float(4)
}
Array
(
    [width] => 3
    [height] => 4
    [area] => 12
)
bool(true)

var_dump() shows only stored values, so $area doesn't appear. get_object_vars() and isset() go through the get hook.

A virtual property can also have a set hook that writes somewhere else. Here $fahrenheit is a second view of $celsius:

<?php
class Temperature
{
    public float $celsius = 0.0;

    // virtual: no storage of its own, reads and writes $celsius
    public float $fahrenheit {
        get => $this->celsius * 9 / 5 + 32;
        set {
            $this->celsius = ($value - 32) * 5 / 9;
        }
    }
}

$t = new Temperature();
$t->fahrenheit = 212;
echo $t->celsius, "\n";
$t->celsius = 37;
echo $t->fahrenheit, "\n";
var_dump($t);

$rp = new ReflectionProperty(Temperature::class, 'fahrenheit');
var_dump($rp->isVirtual());

Output:

100
98.6
object(Temperature)#1 (1) {
  ["celsius"]=>
  float(37)
}
bool(true)

Only $celsius is stored, so the two can't get out of sync.

The short set form makes a property backed

set => expr; is shorthand for set { $this->prop = expr; }. The expression's result is stored in the property. That's right for normalization:

<?php
class Article
{
    public string $slug {
        set => strtolower(trim(preg_replace('/[^a-z0-9]+/i', '-', $value), '-'));
    }
}

$a = new Article();
$a->slug = '  Property Hooks in PHP 8.4!  ';
echo $a->slug, "\n";

Output:

property-hooks-in-php-8-4

It's a trap if you use set => to forward a write elsewhere. This version of Temperature looks virtual, but it isn't:

<?php
class Temperature
{
    public float $celsius = 0.0;

    // looks virtual, but "set =>" assigns its result to $this->fahrenheit
    public float $fahrenheit {
        get => $this->celsius * 9 / 5 + 32;
        set => $this->celsius = ($value - 32) * 5 / 9;
    }
}

$t = new Temperature();
$t->fahrenheit = 212;
var_dump($t);
var_dump((new ReflectionProperty(Temperature::class, 'fahrenheit'))->isVirtual());

Output:

object(Temperature)#1 (2) {
  ["celsius"]=>
  float(100)
  ["fahrenheit"]=>
  float(100)
}
bool(false)

The assignment expression evaluates to 100, and that gets stored as a backing value that get never reads. It works, but the object carries a stale copy. To forward a write, use the block form.

Write-only properties

A virtual property with only a set hook can be written but not read. That suits secrets you transform on the way in:

<?php
class Account
{
    public private(set) string $passwordHash = '';

    // virtual, write-only: there is no get hook
    public string $password {
        set {
            if (strlen($value) < 8) {
                throw new InvalidArgumentException('password too short');
            }
            $this->passwordHash = password_hash($value, PASSWORD_DEFAULT);
        }
    }
}

$a = new Account();
$a->password = 'correct horse battery';
var_dump(password_verify('correct horse battery', $a->passwordHash));

try {
    echo $a->password;
} catch (Error $e) {
    echo $e->getMessage(), "\n";
}

Output:

bool(true)
Property Account::$password is write-only

Typed set parameters

By default $value has the property's type. You can name the parameter and give it a wider type, so writes accept more than reads return:

<?php
declare(strict_types=1);

class Event
{
    // reads always return DateTimeImmutable, writes also accept a string
    public DateTimeImmutable $startsAt {
        set(DateTimeImmutable|string $value) {
            $this->startsAt = is_string($value)
                ? new DateTimeImmutable($value)
                : $value;
        }
    }
}

$e = new Event();
$e->startsAt = '2026-11-03 18:30';
echo $e->startsAt->format('D, d M Y H:i'), "\n";

$e->startsAt = new DateTimeImmutable('2027-01-01');
echo $e->startsAt->format('Y-m-d'), "\n";

try {
    $e->startsAt = 42;
} catch (TypeError $err) {
    echo $err->getMessage(), "\n";
}

Output:

Tue, 03 Nov 2026 18:30
2027-01-01
Event::$startsAt::set(): Argument #1 ($value) must be of type DateTimeImmutable|string, int given, called in ... on line 24

The parameter type must include the property type (it's contravariant, like a method parameter). The value you store still has to match the property type DateTimeImmutable. Note the hook's name in the error: Event::$startsAt::set(). That's also what you see in stack traces.

The parameter name doesn't have to be $value: set(string $raw) { ... } works too.

Hooks on promoted constructor parameters

Constructor property promotion supports hooks. The hook runs for the constructor argument too:

<?php
class Product
{
    public function __construct(
        public string $name {
            set => trim($value);
        },
        public int $price {
            set {
                if ($value < 0) {
                    throw new ValueError("price must be >= 0, got $value");
                }
                $this->price = $value;
            }
        },
    ) {}
}

$p = new Product('  Keyboard ', 4999);
var_dump($p->name, $p->price);

try {
    new Product('Mouse', -1);
} catch (ValueError $e) {
    echo $e->getMessage(), "\n";
}

Output:

string(8) "Keyboard"
int(4999)
price must be >= 0, got -1

When hooks run

A default value is assigned directly and does not go through the set hook. Every write after that does, including compound assignments like ++ and +=:

<?php
class Counter
{
    public int $count = 10 {
        set {
            echo "set($value)\n";
            $this->count = $value;
        }
    }
}

$c = new Counter();      // default value does not go through the hook
echo $c->count, "\n";
$c->count = 11;
$c->count++;
$c->count += 5;
echo $c->count, "\n";

Output:

10
set(11)
set(12)
set(17)
17

Hooks also run for accesses from the class's own methods. Only code inside the property's own hooks bypasses them:

<?php
class Box
{
    public int $size {
        get {
            echo "get\n";
            return $this->size;
        }
        set {
            echo "set($value)\n";
            $this->size = $value;
        }
    }

    public function grow(): void
    {
        $this->size += 1;   // inside the class, hooks still run
    }
}

$b = new Box();
$b->size = 1;
$b->grow();
echo $b->size, "\n";

Output:

set(1)
get
set(2)
get
2

So, unlike a private field behind getter methods, a hooked property has no unchecked back door. If a method needs the raw value, store it in a separate private property.

A virtual property can't have a default value (Cannot specify default value for virtual hooked property), because there's nowhere to store it.

Properties in interfaces

Interfaces could only declare methods before 8.4. Now they can require properties, saying whether each one must be readable, writable or both:

<?php
interface Named
{
    public string $name { get; }        // must be readable
}

interface Identified
{
    public int $id { get; set; }        // must be readable and writable
}

// a plain public property satisfies { get; set; }
class Customer implements Named, Identified
{
    public int $id = 0;

    public function __construct(private string $first, private string $last) {}

    // a get hook satisfies { get; }
    public string $name {
        get => "$this->first $this->last";
    }
}

// a public property also satisfies { get; }
class Company implements Named
{
    public function __construct(public string $name) {}
}

function label(Named $n): string
{
    return "<{$n->name}>";
}

$c = new Customer('Ada', 'Lovelace');
$c->id = 7;
echo label($c), ' #', $c->id, "\n";
echo label(new Company('Acme')), "\n";

Output:

<Ada Lovelace> #7
<Acme>

{ get; } is a minimum, not a limit: Company::$name is writable too, and that's allowed. The interface doesn't care whether the property is plain, backed or virtual. Interface properties must be public. A private implementation fails:

Fatal error: Access level to Broken::$name must be public (as in class Named) in ... on line 7

A get-only property can't satisfy { get; set; }. PHP treats the missing hook like a missing method:

Fatal error: Class Broken contains 1 abstract method and must therefore be declared abstract or implement the remaining method (Identified::$id::set) in ... on line 7

See Composition and delegation for an interface property implemented by forwarding to a wrapped object.

Abstract properties

Abstract classes can declare abstract properties with the same { get; } / { set; } / { get; set; } syntax, and they can mix them with concrete hooks:

<?php
abstract class Shape
{
    // subclasses must provide a readable $area
    abstract public float $area { get; }

    // a concrete hook in an abstract class
    public string $summary {
        get => sprintf('%s with area %.2f', static::class, $this->area);
    }
}

class Circle extends Shape
{
    public function __construct(public float $radius) {}

    public float $area {
        get => M_PI * $this->radius ** 2;
    }
}

class Square extends Shape
{
    public function __construct(float $side)
    {
        $this->area = $side * $side;
    }

    // a plain property is also fine
    public float $area;
}

echo (new Circle(1))->summary, "\n";
echo (new Square(3))->summary, "\n";

Output:

Circle with area 3.14
Square with area 9.00

Unlike an interface, an abstract class can declare an abstract property protected.

Overriding hooks and parent::$prop::get()

A child class can redeclare a property to add or replace hooks. To call the parent's hook, use parent::$prop::get() or parent::$prop::set($value):

<?php
class Account
{
    public int $balance = 0 {
        set {
            if ($value < 0) {
                throw new DomainException('balance cannot be negative');
            }
            $this->balance = $value;
        }
    }
}

class AuditedAccount extends Account
{
    public array $log = [];

    // extend the parent's set hook
    public int $balance = 0 {
        set {
            $old = $this->balance;
            parent::$balance::set($value);   // run the parent's validation
            $this->log[] = "$old -> $value"; // only reached if it passed
        }
    }
}

$a = new AuditedAccount();
$a->balance = 100;
$a->balance = 40;
try {
    $a->balance = -5;
} catch (DomainException $e) {
    echo $e->getMessage(), "\n";
}
echo $a->balance, "\n";
print_r($a->log);

Output:

balance cannot be negative
40
Array
(
    [0] => 0 -> 100
    [1] => 100 -> 40
)

Hooks you don't redeclare are inherited. If the parent has no hook of that kind, parent::$prop::get() simply reads the backing value.

Watch out: the redeclaration in AuditedAccount must repeat = 0. Without it the child's property has no default, and the first $this->balance read throws Typed property AuditedAccount::$balance must not be accessed before initialization.

final hooks and final properties

Mark a hook final to stop subclasses from overriding it. This keeps an invariant like "never negative" from being bypassed:

<?php
class Money
{
    public int $cents = 0 {
        final set {
            if ($value < 0) {
                throw new DomainException('negative');
            }
            $this->cents = $value;
        }
    }
}

class Sneaky extends Money
{
    public int $cents = 0 {
        set => $value;
    }
}

Output:

Fatal error: Cannot override final property hook Money::$cents::set() in ... on line 14
Stack trace:
#0 {main}

PHP 8.4 also allows final on the property itself (public final int $y). Then a child can't redeclare it at all: Cannot override final property B::$y.

Restrictions

Hooks are method calls behind property syntax, so some things that work on plain properties don't work on hooked ones:

You try Result
public readonly int $x { get => 1; } Hooked properties cannot be readonly (so a readonly class can't have hooks either)
public static int $x { get => 1; } Cannot declare hooks for static property
unset($obj->x) on a hooked property Cannot unset hooked property A::$x
default value on a virtual property Cannot specify default value for virtual hooked property
$obj->tags[] = 'x' or $r = &$obj->tags when there's a set hook Indirect modification of A::$tags is not allowed

For an immutable computed value, use a get-only virtual property or public private(set) instead of readonly. Immutability covers the trade-offs.

Arrays

The last row of the table is the one you'll hit most. $obj->tags[] = 'x' would modify the array in place without going through set, so PHP forbids it. Assign a whole new array instead:

<?php
class Post
{
    public array $tags = [] {
        set => array_values(array_unique(array_map('strtolower', $value)));
    }

    public function addTag(string $tag): void
    {
        $this->tags = [...$this->tags, $tag];   // goes through the hook
    }
}

$p = new Post();
$p->tags = ['PHP', 'php', 'OOP'];
print_r($p->tags);

try {
    $p->tags[] = 'Hooks';
} catch (Error $e) {
    echo $e->getMessage(), "\n";
}

$p->addTag('Hooks');
print_r($p->tags);

Output:

Array
(
    [0] => php
    [1] => oop
)
Indirect modification of Post::$tags is not allowed
Array
(
    [0] => php
    [1] => oop
    [2] => hooks
)

If you really want in-place modification and don't need a set hook, a get hook can return by reference with &get:

<?php
class Settings
{
    private array $data = ['theme' => 'dark'];

    // &get returns a reference, so callers can modify the array in place
    public array $values {
        &get => $this->data;
    }
}

$s = new Settings();
$s->values['lang'] = 'en';
print_r($s->values);

Output:

Array
(
    [theme] => dark
    [lang] => en
)

That gives away all control over the contents, so it's rarely what you want. For collections with rules, a dedicated collection class with methods is usually better.

Hooks with asymmetric visibility

Asymmetric visibility (public private(set)) controls who can write, and a set hook controls what can be written. They combine well. Here anyone can read the status, only the class can change it, and the hook enforces valid transitions:

<?php
class Order
{
    // anyone can read, only the class can write; the hook still runs
    public private(set) string $status = 'new' {
        set {
            $allowed = ['new' => ['paid'], 'paid' => ['shipped'], 'shipped' => []];
            if (!in_array($value, $allowed[$this->status], true)) {
                throw new LogicException("cannot go from {$this->status} to $value");
            }
            $this->status = $value;
        }
    }

    public function pay(): void  { $this->status = 'paid'; }
    public function ship(): void { $this->status = 'shipped'; }
}

$o = new Order();
$o->pay();
echo $o->status, "\n";

try {
    $o->status = 'shipped';
} catch (Error $e) {
    echo $e->getMessage(), "\n";
}

try {
    (new Order())->ship();
} catch (LogicException $e) {
    echo $e->getMessage(), "\n";
}

Output:

paid
Cannot modify private(set) property Order::$status from global scope
cannot go from new to shipped

The same combination gives you a lazily computed, cached value: a backed property whose get hook fills it on first read.

<?php
class Report
{
    public function __construct(private array $rows) {}

    // backed property used as a cache: computed on first read
    public private(set) ?float $average = null {
        get {
            if ($this->average === null) {
                echo "(computing)\n";
                $this->average = array_sum($this->rows) / count($this->rows);
            }
            return $this->average;
        }
    }
}

$r = new Report([3, 4, 8]);
echo $r->average, "\n";
echo $r->average, "\n";

Output:

(computing)
5
5

Reflection and serialization

Reflection can tell virtual properties apart and call hooks directly:

<?php
class Temperature
{
    public float $celsius = 0.0;

    public float $fahrenheit {
        get => $this->celsius * 9 / 5 + 32;
        set {
            $this->celsius = ($value - 32) * 5 / 9;
        }
    }
}

foreach ((new ReflectionClass(Temperature::class))->getProperties() as $prop) {
    printf(
        "%-10s virtual=%-5s hooks=[%s]\n",
        $prop->getName(),
        var_export($prop->isVirtual(), true),
        implode(', ', array_keys($prop->getHooks())),
    );
}

$t = new Temperature();
$rp = new ReflectionProperty(Temperature::class, 'fahrenheit');
$rp->getHook(PropertyHookType::Set)->invoke($t, 50);
echo $t->celsius, "\n";

echo json_encode($t), "\n";
print_r((array) $t);

Output:

celsius    virtual=false hooks=[]
fahrenheit virtual=true  hooks=[get, set]
10
{"celsius":10,"fahrenheit":50}
Array
(
    [celsius] => 10
)

Different operations treat hooks differently:

Hooks, getter methods or __get?

Use a hook when the value is conceptually a property: a normalized field, a validated field, or a cheap computed value like $fullName or $area. The best part is that you can add one later without breaking callers:

<?php
// version 1: a plain public property
class Point1
{
    public function __construct(public int $x = 0) {}
}

// version 2: same public API, now validated
class Point2
{
    public function __construct(
        public int $x = 0 {
            set => $value >= 0 ? $value : throw new RangeException("x must be >= 0");
        },
    ) {}
}

foreach ([new Point1(), new Point2()] as $p) {
    $p->x = 5;          // caller code is unchanged
    $p->x += 1;
    echo get_class($p), ': ', $p->x, "\n";
}

try {
    $p = new Point2();
    $p->x = -1;
} catch (RangeException $e) {
    echo $e->getMessage(), "\n";
}

Output:

Point1: 6
Point2: 6
x must be >= 0

That removes the main reason for writing trivial getters and setters in PHP.

Use a method when:

Use __get/__set only for truly dynamic property names, like a record wrapping an arbitrary row. They work for every undeclared name at once, but they're untyped, invisible to IDEs and static analysis, and slower. A hook is declared, typed and documented by the class itself. See Magic Methods.

Summary

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents