Skip to content

Document readonly classes #1996

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 4 commits into from
Nov 12, 2022
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
66 changes: 66 additions & 0 deletions language/oop5/basic.xml
Original file line number Diff line number Diff line change
Expand Up @@ -125,6 +125,72 @@ Stack trace:
</screen>
</example>
</warning>

<sect3 xml:id="language.oop5.basic.class.readonly">
<title>Readonly classes</title>
<para>
As of PHP 8.2.0, a class can be marked with the
<modifier>readonly</modifier> modifier.
Marking a class as <modifier>readonly</modifier> will add the
<link linkend="language.oop5.properties.readonly-properties"><modifier>readonly</modifier> modifier</link>
to every declared property, and prevent the creation of
<link linkend="language.oop5.properties.dynamic-properties">dynamic properties</link>.
Moreover, it is impossible to add support for them by using the
<classname>AllowDynamicProperties</classname> attribute. Attempting to do so
will trigger a compile-time error.
</para>
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

maybe you could mention that readonly classes can extend only readonly classes, and non-readonly classes cannot extend readonly ones either.

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Added a paragraph :)

<example>
<programlisting role="php">
<![CDATA[
<?php
#[AllowDynamicProperties]
readonly class Foo {
}

// Fatal error: Cannot apply #[AllowDynamicProperties] to readonly class Foo
?>
]]>
</programlisting>
</example>

<para>
As neither untyped, nor static properties can be marked with the
<literal>readonly</literal> modifier, readonly classes cannot declare
them either:
</para>
<example>
<programlisting role="php">
<![CDATA[
<?php
readonly class Foo
{
public $bar;
}

// Fatal error: Readonly property Foo::$bar must have type
?>
]]>
</programlisting>
<programlisting role="php">
<![CDATA[
<?php
readonly class Foo
{
public static int $bar;
}

// Fatal error: Readonly class Foo cannot declare static properties
?>
]]>
</programlisting>
</example>
<para>
A <modifier>readonly</modifier> class can be
<link linkend="language.oop5.basic.extends">extended</link>
if, and only if, the child class is also a
<modifier>readonly</modifier> class.
</para>
</sect3>
</sect2>

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