Skip to content

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

Closed
@mwaggonerzam

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

Metadata

Metadata

Assignees

Type

No type

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions