Skip to content

Allow default values of readonly properties on PHP 8.6 - #7082

Merged
ondrejmirtes merged 1 commit into
2.3.xfrom
readonly-property-defaults
Nov 15, 2026
Merged

ondrejmirtes merged 1 commit into
2.3.xfrom
readonly-property-defaults

Conversation

@ondrejmirtes

Copy link
Copy Markdown
Member

PHP 8.6 allows readonly properties to declare a default value (RFC, implementation).

  • property.readOnlyDefaultValue is no longer reported when the analysed PHP version is 8.6 or later.
  • The default value initializes the property, so assigning it again in a constructor (including a child class constructor) is reported as assign.readOnlyProperty ("Readonly property X::$foo is already assigned."), same as PHP's "Cannot modify readonly property" error.
  • Reinitialization in __clone() (once), clone-with, and __unserialize() stays allowed, as in PHP.
  • A property with a default value is already treated as initialized by the uninitialized readonly property checks and isset checks; this is now covered by a test.

I went through the tests added in the php-src commit: PHPStan reports no errors where PHP accepts the code, and reports an error wherever PHP throws, except where it is intentionally stricter (uninitialized readonly properties, assignments outside of constructors). The only case not reported is two traits declaring the same property with different default values; PHPStan has no check for incompatible trait property composition at all, independent of readonly.

Closes phpstan/phpstan#15363

PHP 8.6 allows readonly properties to declare a default value
(https://wiki.php.net/rfc/readonly_property_defaults). The default value
initializes the property, so assigning it again in a constructor is reported
as an already assigned readonly property. Reinitialization in __clone() and
__unserialize() stays allowed, same as in PHP.

Amp-Thread-ID: https://ampcode.com/threads/T-01a1dfee-ec21-74a8-a643-d9aba88acbdd
@ondrejmirtes
ondrejmirtes merged commit fd53ef2 into 2.3.x Nov 15, 2026
551 of 556 checks passed
@ondrejmirtes
ondrejmirtes deleted the readonly-property-defaults branch November 15, 2026 16:13
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Readonly property can have a default value since PHP 8.6

1 participant