Skip to content

Readonly Properties Cannot Have Default Values #19173

@adrian-enspired

Description

@adrian-enspired

Description

The following code:

<?php

class X {
    public readonly array $a = [];
}
var_dump(new X()->a);

class Y {
    public function __construct( public readonly array $a = [] ) {}
}

var_dump(new Y()->a);

The X example resulted in this output:

Fatal error: Readonly property X::$a cannot have default value ...

But I expected it to behave similarly / identically to the Y example:

array(0) {
}

Reading the documentation, I do understand that the result I expected initially - i.e., to behave like an argument default value - was misguided. However, I see no reason for a default to be disallowed simply because it would be (in the words of the manual) "essentially the same as a constant" and "not particularly useful." The behavior is inconsistent and unexpected.

Ideally (in my mind, at least) the default value would be assigned if the property was accessed before being initialized, or after construct if it hadn't yet been initialized. But I recognize this would be a larger change in behavior and likely much more complicated to implement.

PHP Version

PHP 8.4.10

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