Skip to content

[Php80] Keep property type safe in ClassPropertyAssignToConstructorPromotionRector - #9049

Merged
TomasVotruba merged 1 commit into
mainfrom
promotion-keep-property-type
Nov 23, 2026
Merged

TomasVotruba merged 1 commit into
mainfrom
promotion-keep-property-type

Conversation

@TomasVotruba

Copy link
Copy Markdown
Member

Promotion puts the param type on the property, which could change the property type in two unsafe ways.

1. Untyped public property in a final class got a native type with the default config

final class Person
{
    public $name;

    public function __construct(string $name = '')
    {
        $this->name = $name;
    }
}

was changed to public function __construct(public string $name = ''). An outside $person->name = null then throws a TypeError, and $person->name = 5 silently becomes "5". The inline_public option documents that without it a public/protected property is only promoted when typed, but the final class check returned early before that. Now the final class shortcut applies only to non-public properties (a protected one in a final class still promotes, as before).

2. Property type narrowed to the param type, even with other writes

final class Canvas
{
    private Shape $shape;

    public function __construct(Circle $shape)
    {
        $this->shape = $shape;
    }

    public function reset(): void
    {
        $this->shape = new Square();
    }
}

was changed to private Circle $shape, so reset() throws a TypeError. Only literal null writes were guarded. Now when the param type differs from the property type, promotion is skipped if the property is assigned anywhere else in the class.

Two FixturePhp80 fixtures relied on bug 1 - their property is now private, keeping what they test (the default value union).

@TomasVotruba
TomasVotruba force-pushed the promotion-keep-property-type branch from 50b4df8 to b51399e Compare November 23, 2026 22:35
@TomasVotruba
TomasVotruba merged commit 54ab447 into main Nov 23, 2026
@TomasVotruba
TomasVotruba deleted the promotion-keep-property-type branch November 23, 2026 22:35
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Development

Successfully merging this pull request may close these issues.

1 participant