Skip to content

Fix #12250: False positive Property HelloWorld::$bug (WeakMap<stdClass, stdClass>) does not accept WeakMap<object, mixed>|WeakMap<stdClass, stdClass>.#4958

Open
phpstan-bot wants to merge 2 commits into2.1.xfrom
create-pull-request/patch-0tutheo
Open

Fix #12250: False positive Property HelloWorld::$bug (WeakMap<stdClass, stdClass>) does not accept WeakMap<object, mixed>|WeakMap<stdClass, stdClass>.#4958
phpstan-bot wants to merge 2 commits into2.1.xfrom
create-pull-request/patch-0tutheo

Conversation

@phpstan-bot
Copy link
Collaborator

@phpstan-bot phpstan-bot commented Feb 16, 2026

Summary

When a generic class like WeakMap is instantiated and assigned to a typed property using the null coalesce assignment operator (??=), PHPStan failed to infer the generic type parameters from the property's declared type. This caused a false positive like:

Property HelloWorld::$bug (WeakMap<stdClass, stdClass>) does not accept WeakMap<object, mixed>|WeakMap<stdClass, stdClass>.

Changes

  • Modified src/Parser/NewAssignedToPropertyVisitor.php to also handle Node\Expr\AssignOp\Coalesce in addition to Assign and AssignRef
  • Added regression test tests/PHPStan/Rules/Properties/data/bug-12250.php
  • Added test method testBug12250() in tests/PHPStan/Rules/Properties/TypesAssignedToPropertiesRuleTest.php

Root cause

NewAssignedToPropertyVisitor is a parser visitor that marks new expressions assigned to properties with an attribute, so that MutatingScope::exactInstantiation() can later infer generic type parameters from the property's declared type. The visitor handled Assign (=) and AssignRef (=&), but not AssignOp\Coalesce (??=). Without the attribute, new WeakMap() in $this->bug ??= new WeakMap() was typed as WeakMap<object, mixed> (the default generic bounds) instead of WeakMap<stdClass, stdClass> (from the property declaration).

Test

The regression test verifies that $this->bug ??= new WeakMap() produces no errors when the property is typed as WeakMap<stdClass, stdClass>, alongside a regular assignment $this->ok = new WeakMap() that already worked correctly.

Fixes phpstan/phpstan#12250

Closes phpstan/phpstan#4525

phpstan-bot and others added 2 commits February 16, 2026 20:33
- Added handling for AssignOp\Coalesce in NewAssignedToPropertyVisitor
- The visitor now marks `new` expressions in `$this->prop ??= new Foo()` with the property attribute, so MutatingScope::exactInstantiation() can infer generic type parameters from the property's declared type
- New regression test in tests/PHPStan/Rules/Properties/data/bug-12250.php

Closes phpstan/phpstan#12250
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.

1 participant