Skip to content

Update trait docs for PHP-8.2 #1995

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 2 commits into from
Nov 30, 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
62 changes: 58 additions & 4 deletions language/oop5/traits.xml
Original file line number Diff line number Diff line change
Expand Up @@ -466,8 +466,8 @@ $example->x;
</example>
<para>
If a trait defines a property then a class can not define a property with
the same name unless it is compatible (same visibility and initial value),
otherwise a fatal error is issued.
the same name unless it is compatible (same visibility and type,
readonly modifier, and initial value), otherwise a fatal error is issued.
</para>
<example xml:id="language.oop5.traits.properties.conflicts">
<title>Conflict Resolution</title>
Expand All @@ -476,20 +476,74 @@ $example->x;
<?php
trait PropertiesTrait {
public $same = true;
public $different = false;
public $different1 = false;
public bool $different2;
readonly public bool $different3;
}

class PropertiesExample {
use PropertiesTrait;
public $same = true;
public $different = true; // Fatal error
public $different1 = true; // Fatal error
public string $different2; // Fatal error
readonly public bool $different3; // Fatal error
}
?>
]]>
</programlisting>
</example>
</sect2>

<sect2 xml:id="language.oop5.traits.constants">
<title>&Constants;</title>
<para>
Traits can, as of PHP 8.2.0, also define constants.
</para>
<example xml:id="language.oop5.traits.constants.example">
<title>Defining Constants</title>
<programlisting role="php">
<![CDATA[
<?php
trait ConstantsTrait {
public const FLAG_MUTABLE = 1;
final public const FLAG_IMMUTABLE = 5;
}

class ConstantsExample {
use ConstantTrait;
}

$example = new ConstantExample;
$example::FLAG;
?>
]]>
</programlisting>
</example>
<para>
If a trait defines a constants then a class can not define a constants with
the same name unless it is compatible (same visibility, initial value, and
finality), otherwise a fatal error is issued.
</para>
<example xml:id="language.oop5.traits.constants.conflicts">
<title>Conflict Resolution</title>
<programlisting role="php">
<![CDATA[
<?php
trait ConstantsTrait {
public const FLAG_MUTABLE = 1;
final public const FLAG_IMMUTABLE = 5;
}

class ConstantsExample {
use ConstantTrait;
public const FLAG_IMMUTABLE = 5; // Fatal error
}
?>
]]>
</programlisting>
</example>
</sect2>

</sect1>
<!-- Keep this comment at the end of the file
Local variables:
Expand Down