Skip to content

PHP 8.2 readonly classes allow inheriting mutable properties from traits #9285

Closed
@TysonAndre

Description

@TysonAndre

Description

The following code:

<?php
trait T2{ public $prop; }
readonly class G { use T2; }
$g = new G();
$g->prop = 123;
$g->prop = 124;
var_export($g);

Resulted in this output:

\G::__set_state(array(
   'prop' => 124,
))

But I expected this output instead:

One of the following

  1. Making the inherited properties readonly (seems strange and makes trait harder to reason about without knowing about uses) - also, the readonly keyword can already be used
  2. Making it an error to inherit a property from a trait at the time of inheritance when all trait properties are determined (including traits extending other traits)
    EDIT: Or just non-readonly properties
  3. Making it an error to use traits from readonly classes (similar to existing check that makes it an error to extend from non-readonly classes, including classes that have no properties)
  4. readonly trait support, which requires its own rfc. Ideas:
    a. (can only be used by readonly classes and readonly traits?)
    b. EDIT: A better restriction might be that they can have properties, but all properties declared within the trait or inherited by the trait must be readonly (allow them to modify properties declared elsewhere, which should rarely be needed)

So far, the only reference to traits in the implementation was just checking that the modifier couldn't be applied to traits (https://github.com/php/php-src/pull/7305/files#diff-3fa220fdd8047943b96515df0805331f7ae6d52a0228084d5e9b491e8f1b01a9)

PHP Version

PHP 8.2.0beta2

Operating System

No response

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions