What's a readonly Class Used for in PHP?

A readonly class can be great way for creating value-objects in PHP:

// PHP 8.2+
readonly class Person
{
    public function __construct(
        public string $name,
        public int $age,
    ) {}
}

$person = new Person('John', 42);

echo "$person->name is $person->age years old"; // John is 42 years old

However, in a more general sense, a readonly class in PHP is used for:

  • Implicitly making all instance properties of a class readonly;
  • Preventing the creation of dynamic properties (even with the #[AllowDynamicProperties] attribute).

For example:

// PHP 8.2+
readonly class Foo
{
    public int $bar;

    public function __construct() {
        $this->bar = 1;
    }
}

$foo = new Foo();

// Fatal error: Uncaught Error: Cannot modify readonly property Foo::$bar ...
$foo->bar = 2;

// Fatal error: Uncaught Error: Cannot create dynamic property Foo::$baz ...
$foo->baz = 1;

To not violate the readonly constraint, adding the #[AllowDynamicProperties] attribute to a readonly class will throw a compile-time error:

// PHP 8.2+
// Fatal error: Cannot apply #[AllowDynamicProperties] to readonly class Foo ...
#[AllowDynamicProperties]
readonly class Foo { /* ... */ }

Please note that readonly classes cannot have untyped or static properties.


Hope you found this post useful. It was published . Please show your love and support by sharing this post.