Can't use inherited constant value via 'self' in enum case value
Description
The following code:
<?php
interface I {
public const DEFAULT_VALUE = 'gambrinus';
}
enum Beer: string implements I {
// case GAMBRINUS = I::DEFAULT_VALUE;
case GAMBRINUS = self::DEFAULT_VALUE;
}
var_dump(Beer::GAMBRINUS);
Resulted in this output:
Fatal error: Enum case value must be compile-time evaluatable in /in/Oqm7f on line 9
But I expected this output instead:
No errors, because commented case GAMBRINUS = I::DEFAULT_VALUE produces no error
PHP Version
8.1.1
Operating System
No response
It seems I didn't fully understood compile-time semantics, can be closed.
Not so fast; https://3v4l.org/5sZes works.
The problem here is that we compute a value to case table during compilation and all values must be known at that time. This happens pre-inheritance, so self::DEFAULT_VALUE is unknown at the time. This is unfortunate from a language design perspective, because what exactly can be evaluated during compilation and what can't is essentially an implementation detail (and may depend on whether opcache is used or not).
I think it should be possible to make this part of inheritance instead, which should allow us to evaluate all expressions. It would also delay some error reporting (about duplicate case values) to that point.
Found another interesting feature-bug:
class Example
{
final public const TEST = 42;
}
enum ExampleEnum: int
{
case CASE = Example::TEST;
}
- If you run the code for the first time, then it works
- If you run the code again (PHP 8.1.4), an error occurs:
Enum case value must be compile-time evaluatable
There is a suspicion that this is somehow related to opcache:
$ php test.php -dopcache.jit_buffer_size=0 -dopcache.enable=1 -dopcache.enable_cli=0
// - First execution 42
// - Second execution 42
// - Third execution 42
$ php test.php -dopcache.jit_buffer_size=0 -dopcache.enable=1 -dopcache.enable_cli=1
// - First execution 42
// - Second execution: Enum case value must be compile-time evaluatable
// - Third execution: Enum case value must be compile-time evaluatable
P.S.
PHP 8.1.4 (cli) (built: Apr 4 2022 13:30:33) (NTS)
Copyright (c) The PHP Group
Zend Engine v4.1.4, Copyright (c) Zend Technologies
with Zend OPcache v8.1.4, Copyright (c), by Zend Technologies
Does it make sense to try to reproduce the behavior in other versions of the language (8.1.3, 8.1.2, etc)?
@SerafimArts Thanks! I think this should also be solved by #8190 but I'll make sure to add a test. You don't have to test it for older patches, not much has changed in the patches for enums. Edit: Although this qualifies as a bug. I'll see if I can fix that for 8.1.
Edit: Although this qualifies as a bug. I'll see if I can fix that for 8.1.
Yea. Let me move this information into a separate issue?
@SerafimArts Feel free to create a new issue.
@iluuu1994 Yes, I'm sorry, that's probably how it should have been done initially, so as not to confuse different situations.