Skip to content

Fix phpstan/phpstan#14251: new X() where X is a trait should be reported#5182

Merged
ondrejmirtes merged 1 commit intophpstan:2.1.xfrom
phpstan-bot:create-pull-request/patch-qm45vdf
Mar 10, 2026
Merged

Fix phpstan/phpstan#14251: new X() where X is a trait should be reported#5182
ondrejmirtes merged 1 commit intophpstan:2.1.xfrom
phpstan-bot:create-pull-request/patch-qm45vdf

Conversation

@phpstan-bot
Copy link
Collaborator

Summary

PHPStan was not reporting an error when trying to instantiate a trait with new TraitName(). The InstantiationRule already checks for enums, interfaces, and abstract classes but was missing a check for traits.

Changes

  • Added trait instantiation check in src/Rules/Classes/InstantiationRule.php, before the existing enum/interface/abstract checks
  • Error message follows the same pattern as interfaces: "Cannot instantiate trait X." with identifier new.trait
  • Added regression test in tests/PHPStan/Rules/Classes/data/bug-14251.php and corresponding test method in tests/PHPStan/Rules/Classes/InstantiationRuleTest.php

Root cause

The InstantiationRule had checks for isEnum(), isInterface(), and isAbstract() on the class reflection, but was missing a check for isTrait(). Traits cannot be instantiated in PHP (it produces a fatal error), so PHPStan should report this statically.

Test

Added testBug14251() which verifies that new InternalTrait() produces the error "Cannot instantiate trait Bug14251\InternalTrait." at line 9.

Fixes phpstan/phpstan#14251

- Added trait check to InstantiationRule alongside existing checks for enums, interfaces, and abstract classes
- New error message: "Cannot instantiate trait X." with identifier "new.trait"
- New regression test in tests/PHPStan/Rules/Classes/data/bug-14251.php

Closes phpstan/phpstan#14251
@ondrejmirtes ondrejmirtes merged commit 54f3522 into phpstan:2.1.x Mar 10, 2026
122 of 131 checks passed
@ondrejmirtes ondrejmirtes deleted the create-pull-request/patch-qm45vdf branch March 10, 2026 13:06
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.

2 participants