Readonly deep dive
A readonly property of PHP is written once and then only read, which turns a class into a value object that is safe to pass around. The blocks below write one, break the rule on purpose and copy an object the supported way.
Readonly props
A readonly property can be written only once. The constructor is the usual place for that single write.
After the first write the value stays fixed, which makes small value objects safe to share across the codebase.
<?php class User { public readonly string $name; public function __construct(string $name) { $this->name = $name; } } $user = new User("Ann"); echo $user->name, PHP_EOL; try { $user->name = "Bob"; } catch (Error $e) { echo get_class($e), ": ", $e->getMessage(), PHP_EOL; }
php props.php
Ann
Error: Cannot modify readonly property User::$name
The first write happened in the constructor and was allowed. The second one threw an Error whose message names the property, and the program kept running because the call was wrapped in a catch.
Readonly classes
A readonly class marks every property as readonly at once. You write the keyword once on the class instead of repeating it on each property.
Every property in such a class must carry a type. Static properties are not allowed there, which keeps the class a plain data holder.
<?php readonly class Point { public function __construct( public float $x, public float $y, ) { } } $p = new Point(1.5, 2.0); echo $p->x, ", ", $p->y, PHP_EOL;
php classes.php
1.5, 2
Promotion in the constructor counts as the single write of a readonly class, so the object is complete the moment new returns.
Clone to modify
A readonly property cannot be reassigned, so cloning is the way to a changed copy. Clone the object and the copy starts with the same values.
Newer PHP adds a shortcut for this pattern, see clone with overrides in PHP 8.5 for the short form.
<?php class User { public readonly string $name; public function __construct(string $name) { $this->name = $name; } public function withName(string $name): self { return clone($this, ["name" => $name]); } } $a = new User("Ann"); $b = clone $a; echo $b->name, PHP_EOL; $c = $a->withName("Bob"); echo $a->name, PHP_EOL, $c->name, PHP_EOL; echo $a === $c ? "same" : "different", PHP_EOL;
php clone.php
Ann
Ann
Bob
different
A plain clone copies the value, and the 8.5 form copies it with one property replaced. The original keeps the old name, which is the point of a copy.
Limits
Readonly has clear limits. A readonly property must be typed and cannot be static, and the single write cannot happen twice.
Plan the constructor so it receives every value up front. Later code only reads, which removes a whole group of state bugs.
<?php class Config { public function __construct( public readonly string $host, public readonly int $port, ) { } } $config = new Config("localhost", 8080); echo $config->host, ":", $config->port, PHP_EOL; try { $config->port = 9090; } catch (Error $e) { echo $e->getMessage(), PHP_EOL; }
php limits.php
localhost:8080
Cannot modify readonly property Config::$port
The constructor is the only writer, and an attempt from outside reaches the same error as before.
Exercises
- Give a readonly class a method that returns a new instance with one value replaced.
- Try to declare a static property in a readonly class and describe the error.
- Write a readonly property without a type and read the message PHP returns.
- Clone an object with an array property and check whether the array is shared with the copy.
- Replace a settable configuration object with a readonly one and update the callers.
Questions
A new set of questions in a new order every time. Choose one answer for each, then check.
-
How many times may a readonly property be written?
Answer
Once
The first write initialises it and any later write throws an Error.
-
What does the
readonlykeyword on a class do?Answer
It makes every property readonly and requires a type on each
The class-level keyword applies to all properties at once and static properties are refused.
-
Why is cloning the way to a changed readonly object?
Answer
The copy can be initialised with new values while the original stays untouched
The 8.5 clone form sets chosen properties on the fresh copy, and the original keeps its values.
-
Which property is not allowed in a readonly class?
Answer
A static property
A static property belongs to the class rather than to an instance, so readonly cannot apply to it.
-
What does this program print?
<?php class User { public readonly string $name; public function __construct(string $name) { $this->name = $name; } } $user = new User("Ann"); echo $user->name;Answer
Ann
The constructor holds the single allowed write, and the echo only reads it.
-
What does this program print?
<?php class User { public readonly string $name; public function __construct(string $name) { $this->name = $name; } } $user = new User("Ann"); try { $user->name = "Bob"; } catch (Error $e) { echo get_class($e); }Answer
Error
A write to a readonly property throws the base Error class, not an Exception.
-
What does this program print?
<?php readonly class Point { public function __construct( public float $x, public float $y, ) { } } $p = new Point(1.5, 2.0); echo $p->x, " ", $p->y;Answer
1.5 2
Both promoted properties are written by the constructor, and a float of 2 prints without decimals.
-
What does this program print?
<?php class User { public readonly string $name; public function __construct(string $name) { $this->name = $name; } public function withName(string $name): self { return clone($this, ["name" => $name]); } } $a = new User("Ann"); $c = $a->withName("Bob"); echo $a->name, " ", $c->name;Answer
Ann Bob
The clone takes the new name and the original keeps the one it was built with.
-
What does a plain
clone $objectgive you for a readonly property?Answer
A copy with the same value
Cloning copies the current values; the copy is a new object with the same data.
-
What error does a write to a readonly property throw?
Answer
An Error with a message that names the property
PHP refuses the write at run time with an Error such as Cannot modify readonly property Config::$port.
The code on this page was run with PHP 8.5.13 (php -v) in Alpine Linux, with the commands shown above.
Article author: Arthur Isaev