php / php/php-src

Fatal error: class and trait define the same constant in the composition of child class in case constant in trait is equal to constant in child class

Open
#9,272 2 comments 3 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

Bug Category: Engine Status: Needs Triage
Dominant language
C
Stars
40.4k
Forks
8.1k
Avg merge
2d 13h
Merged PRs (30d)
96

Description

Description

The following code:

<?php
trait T {
    public const a = C2::b;
}
class C1 {
    use T;
    const b = 1;
}
class C2 extends C1  {
    use T;
    const b = 2;
}
echo C1::a;
echo C2::a;

Resulted in this output:

Fatal error: C1 and T define the same constant (a) in the composition of C2. However, the definition differs and is considered incompatible. Class was composed in /in/riAnX on line 9

But I expected this output instead:

22

It's not clear to me why this code is incorrect, but at the same time, the following works:

<?php
trait T {
    public const a = self::b;
}
class C1 {
    use T;
    const b = 1;
}
class C2 extends C1  {
    use T;
    const b = 2;
}
echo C1::a;
echo C2::a;

and outputs

11
PHP Version

8.2

Operating System

No response

Contributor guide

Open the contributing guide

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

Research direction

No source file or test is named. Start by running the provided PHP 8.2 reproducer and compare the trait constant using C2::b with the self::b variant; trace trait/class constant composition to establish the intended rule. Done means the first example follows the intended constant-resolution behavior without an incorrect fatal error, with regression coverage.

Written by the indexing model from the issue text.

Assessment

Tech stack
php
Domain
backend
Issue type
Bug
Difficulty
4/5
Estimated time
3-5 days
Activity status
Stale
Clarity
Mostly clear
Newbie friendliness
35/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.