Skip to content

Fix #11351: Defining Array Constants in PHP Traits Causes Errors When Using Class Constants as Keys or Values#5101

Open
phpstan-bot wants to merge 1 commit intophpstan:2.1.xfrom
phpstan-bot:create-pull-request/patch-7z2rj8x
Open

Fix #11351: Defining Array Constants in PHP Traits Causes Errors When Using Class Constants as Keys or Values#5101
phpstan-bot wants to merge 1 commit intophpstan:2.1.xfrom
phpstan-bot:create-pull-request/patch-7z2rj8x

Conversation

@phpstan-bot
Copy link
Collaborator

Summary

When a trait defines an array constant that uses self::CONST as a key or value, PHPStan incorrectly reported "overriding constant with different value" because it resolved the trait constant's value expression in the trait's own context (where the class constant doesn't exist), rather than in the using class's context (where self actually resolves at runtime).

Changes

  • Modified src/Rules/Traits/ConflictingTraitConstantsRule.php: Changed the InitializerExprContext used to evaluate the trait constant value from InitializerExprContext::fromClass(traitName, ...) to InitializerExprContext::fromClassReflection($classReflection), so that self:: references in trait constants are resolved in the using class's context.

Root cause

In ConflictingTraitConstantsRule, when comparing a class constant value against the trait constant value it overrides, the trait constant's value expression was evaluated using InitializerExprContext::fromClass() with the trait's class name. This meant self::CA in the trait couldn't find CA (defined in the using class), producing a generic non-empty-array<int|string, 'CA'> type instead of the specific array{abc: 'CA'}. The fix evaluates the trait constant in the using class's context, matching PHP's actual self resolution semantics in traits.

Test

Added tests/PHPStan/Rules/Traits/data/bug-11351.php with two test cases:

  • Trait constant using self::CA as an array key
  • Trait constant using self::CB as an array value

Both expect no errors (the previous false positives are eliminated).

Fixes phpstan/phpstan#11351

… keys/values

- Trait constant values were resolved in the trait's own context, causing self:: references to class constants to be unresolvable
- Changed ConflictingTraitConstantsRule to evaluate trait constant values in the using class context, since self in a trait resolves to the using class
- New regression test in tests/PHPStan/Rules/Traits/data/bug-11351.php

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