PHP Reference ยท Functions and Classes
Asymmetric visibility (PHP 8.4)
Reference for PHP 8.4 asymmetric visibility: public private(set) and protected(set) properties, rules, readonly interaction, inheritance and errors.
Asymmetric visibility, added in PHP 8.4, lets a property have one visibility for reading and a stricter one for writing. The most common form is public private(set): anyone can read the property, but only code inside the class can assign it.
It replaces the old pattern of a private property plus a public getter. The property stays a normal property, so callers write $object->count and you keep full control over who changes it.
class Counter { public private(set) int $count = 0; }
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 private(set) Type $name; public protected(set) Type $name; protected private(set) Type $name; // read in subclasses, write only here public function __construct(public private(set) Type $name) {}
The first keyword is the read visibility. (set) visibility must be the same as or stricter than the read visibility.
Errors: writing from outside the allowed scope throws Error ("Cannot modify private(set) property ...").
Usage notes
- Typed properties only. An asymmetric property must have a type declaration.
private(set)means the class that declared it. Even a child class cannot write it, as the second example shows. Useprotected(set)to let subclasses write.- Shorter form.
private(set) int $xalone meanspublic private(set) int $x. readonlyis related. Areadonlyproperty is implicitlyprivate(set)and can be written only once. Asymmetric visibility withoutreadonlyallows many writes from inside.- References and arrays. The property cannot be modified indirectly from outside:
$counter->count++and$list->items[] = 1fail too. Taking a reference is only allowed where writing is. - Instance properties. PHP 8.4 supports the feature for instance properties; check the version notes before using it on static ones.
- Interfaces can declare
public string $name { get; }; asymmetric visibility is the usual way to implement such a requirement with a plain property. - Compared with hooks. Use property hooks when reading or writing must run logic; use asymmetric visibility when the problem is only who may write.