Skip to content

isset() on readonly properties in constructors & inheritance #9863

@levu42

Description

@levu42

Bug report

Disclaimer I'm not even sure whether there's a PHP bug as well inside, but there's at least one PHPStan bug in it.

My basic objective is to have a class with a readonly property that's assigned once in the constructor, and a child class having a constructor with a default value for that readonly property.

(Real world example: class Unit, new Unit('kg'), class WeightUnit extends Unit, new WeightUnit() with 'kg' being the default.)

I couldn't find anything in the PHP specs regarding readonly & inheritance, so I just assumed that the child constructor is called, the property set, then the parent constructor is called, and it needs to check whether the readonly property is already set (if it's called from a child constructor) or not (called directly) before trying to set it itself.

So I think one PHPStan at least is to not report the usage of isset() in a constructor on a readonly property when the class isn't final. The other bug (feature request?) is to recognize the PHP fatal error when a constructor calls a parent constructor that sets a readonly property after the child constructor already set it.

Code snippet that reproduces the problem

https://phpstan.org/r/56181865-dda9-4e35-bf25-571ef2deb066

Expected output

  • I expected an error in line 15 (parent::__construct($foo)) because PHP throws a Fatal error there, but none was reported

  • I expected no errors in the WithIsset part, because that seems to work with PHP 8.2

PS: BTW: I figured out, how to do it way cleaner, but this was an intermediate step, and I wanted to report it, so I don't need any advice in that regard, but PHPStan's reported errors should still align with PHP's fatal errors :)

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions