Skip to content

Commit 5126704

Browse files
Girgiasmumumucmb69
authored
Document readonly classes (#1996)
Co-authored-by: Yoshinari Takaoka <[email protected]> Co-authored-by: Christoph M. Becker <[email protected]>
1 parent eb1f127 commit 5126704

File tree

1 file changed

+66
-0
lines changed

1 file changed

+66
-0
lines changed

language/oop5/basic.xml

Lines changed: 66 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -125,6 +125,72 @@ Stack trace:
125125
</screen>
126126
</example>
127127
</warning>
128+
129+
<sect3 xml:id="language.oop5.basic.class.readonly">
130+
<title>Readonly classes</title>
131+
<para>
132+
As of PHP 8.2.0, a class can be marked with the
133+
<modifier>readonly</modifier> modifier.
134+
Marking a class as <modifier>readonly</modifier> will add the
135+
<link linkend="language.oop5.properties.readonly-properties"><modifier>readonly</modifier> modifier</link>
136+
to every declared property, and prevent the creation of
137+
<link linkend="language.oop5.properties.dynamic-properties">dynamic properties</link>.
138+
Moreover, it is impossible to add support for them by using the
139+
<classname>AllowDynamicProperties</classname> attribute. Attempting to do so
140+
will trigger a compile-time error.
141+
</para>
142+
<example>
143+
<programlisting role="php">
144+
<![CDATA[
145+
<?php
146+
#[AllowDynamicProperties]
147+
readonly class Foo {
148+
}
149+
150+
// Fatal error: Cannot apply #[AllowDynamicProperties] to readonly class Foo
151+
?>
152+
]]>
153+
</programlisting>
154+
</example>
155+
156+
<para>
157+
As neither untyped, nor static properties can be marked with the
158+
<literal>readonly</literal> modifier, readonly classes cannot declare
159+
them either:
160+
</para>
161+
<example>
162+
<programlisting role="php">
163+
<![CDATA[
164+
<?php
165+
readonly class Foo
166+
{
167+
public $bar;
168+
}
169+
170+
// Fatal error: Readonly property Foo::$bar must have type
171+
?>
172+
]]>
173+
</programlisting>
174+
<programlisting role="php">
175+
<![CDATA[
176+
<?php
177+
readonly class Foo
178+
{
179+
public static int $bar;
180+
}
181+
182+
// Fatal error: Readonly class Foo cannot declare static properties
183+
?>
184+
]]>
185+
</programlisting>
186+
</example>
187+
<para>
188+
A <modifier>readonly</modifier> class can be
189+
<link linkend="language.oop5.basic.extends">extended</link>
190+
if, and only if, the child class is also a
191+
<modifier>readonly</modifier> class.
192+
</para>
193+
</sect3>
128194
</sect2>
129195

130196
<sect2 xml:id="language.oop5.basic.new">

0 commit comments

Comments
 (0)