[DOC-CVS] [doc-en] master: Document that readonly properties cannot be initialized by reference (#5226)
[email protected] (Louis-Arnaud via GitHub)
| Newsgroups | php.doc.cvs |
|---|---|
| Message-ID | <[email protected]> |
Author: Louis-Arnaud (lacatoire)
Committer: GitHub (web-flow)
Pusher: lacatoire
Date: 2026-08-28T17:02:09+02:00
Commit: https://github.com/php/doc-en/commit/4e77868e15fea65175b87a38d6d31b61d63f7f8e
Raw diff: https://github.com/php/doc-en/commit/4e77868e15fea65175b87a38d6d31b61d63f7f8e.diff
Document that readonly properties cannot be initialized by reference (#5226)
Clarify that readonly properties must be initialized through direct
assignment and cannot be initialized via by-reference parameters.
Fixes https://github.com/php/doc-en/issues/3250
Changed paths:
M language/oop5/properties.xml
Diff:
diff --git a/language/oop5/properties.xml b/language/oop5/properties.xml
index a40df2528bab..a3e7f23a00ae 100644
--- a/language/oop5/properties.xml
+++ b/language/oop5/properties.xml
@@ -257,6 +257,35 @@ $test1->prop = "foobar";
</programlisting>
</example>
</para>
+ <note>
+ <para>
+ Readonly properties can only be initialized by a direct assignment.
+ An uninitialized readonly property cannot be initialized by reference, not even
+ from the scope where it has been declared: passing it to a function parameter that
+ expects to be passed by reference, or assigning it by reference, results in an
+ <exceptionname>Error</exceptionname> exception.
+ <informalexample>
+ <programlisting role="php" annotations="non-interactive">
+<![CDATA[
+<?php
+
+class Test {
+ public readonly array $matches;
+
+ public function __construct(string $subject) {
+ // Illegal initialization by reference.
+ preg_match('/\d+/', $subject, $this->matches);
+ // Error: Cannot indirectly modify readonly property Test::$matches
+ }
+}
+
+new Test('abc 42');
+?>
+]]>
+ </programlisting>
+ </informalexample>
+ </para>
+ </note>
<note>
<para>
Specifying an explicit default value on readonly properties is not allowed, because a readonly property with a default value is essentially the same as a constant, and thus not particularly useful.