Skip to content
Tutorials Center
My learning

Topics

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.

PHP
class Counter
{
    public private(set) int $count = 0;
}

Try it

PHP Public to read, private to write

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.

PHP protected(set) and promoted properties

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

PHP
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. Use protected(set) to let subclasses write.
  • Shorter form. private(set) int $x alone means public private(set) int $x.
  • readonly is related. A readonly property is implicitly private(set) and can be written only once. Asymmetric visibility without readonly allows many writes from inside.
  • References and arrays. The property cannot be modified indirectly from outside: $counter->count++ and $list->items[] = 1 fail 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.