Skip to content

Using enum as array key in class constant correctly results in error, but line number is inaccurate #8821

Closed

Description

@mwaggonerzam

Description

The following code:

<?php

enum Alpha {
    case Foo;
}

class Bravo {
    public const C = [Alpha::Foo => 3];
}

new Bravo();

Resulted in this output:

Fatal error: Uncaught TypeError: Illegal offset type in /file.php:11
Stack trace:
#0 {main}
  thrown in /file.php on line 11

But I expected this output instead:

Fatal error: Uncaught TypeError: Illegal offset type in /file.php:8
Stack trace:
#0 {main}
  thrown in /file.php on line 8

tl;dr: Yes, I know you can't use an enum as an array key. The problem here is that PHP reported the error as being on the wrong line, making the real problem hard to find.

To elaborate: PHP tells me the error is at new Bravo(), but the actual problem is on the line where the const is defined. In the trivial case above, figuring it out is easy, but in actual production code, the new might be in another file entirely and class Bravo might be hundreds of lines long, concealing where the error really is. Yes, I know static analysis tools would correctly find the problem; this is still an error in PHP's engine.

I reproduced this using 3v4l.org, in addition to on my local machine, just to make sure any of my ini settings or extensions weren't affecting things.

PHP Version

PHP 8.1.7

Operating System

No response

Activity

  1. iluuu1994 commented on Jun 17, 2022

    @iluuu1994
    Member

    I think #8124 should cover this. 3v4l master might not be up to date.

  2. mwaggonerzam commented on Jun 17, 2022

    @mwaggonerzam
    Author

    I think #8124 should cover this. 3v4l master might not be up to date.

    Maybe I misunderstand, but it looks like that PR was closed without merging. So I'm not sure how it would have gotten into master.

  3. iluuu1994 commented on Jun 17, 2022

    @iluuu1994
    Member

    We don't always merge via GitHub, the merged commit is e3ef7bb.

  4. iluuu1994 commented on Jun 17, 2022

    @iluuu1994
    Member

    I checked, doesn't look like the correct line is reported on master. I'll have a look.

  5. self-assigned this
    on Jun 17, 2022
  6. mwaggonerzam commented on Jun 17, 2022

    @mwaggonerzam
    Author

    Thanks!

  7. added a commit that references this issue on Feb 2, 2023
    b00d3a7
  8. added a commit that references this issue on Jul 8, 2026
    9e09782
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

Type

No type

Projects

No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions