Closed as not planned
Description
Description
The following code (https://3v4l.org/o5uHL#v8.3.0):
<?php
declare(strict_types=1);
enum IntBacked: int {
case One = 1;
}
var_export(IntBacked::tryFrom('bogus'));
Resulted in this output:
Fatal error: Uncaught TypeError: IntBacked::tryFrom(): Argument #1 ($value) must be of type int, string given in /in/XN86X:9
Stack trace:
#0 /in/XN86X(9): IntBacked::tryFrom('bogus')
#1 {main}
thrown in /in/XN86X on line 9
Process exited with code 255.
But I expected this output instead:
NULL
Explanation:
The typing for BackedEnum is declared as:
interface BackedEnum extends UnitEnum
{
public static function from(int|string $value): static;
public static function tryFrom(int|string $value): ?static;
}
but this is clearly wrong because int backed enums only allow int $value
's and string backed enums only allow string $value
's.
I think the real typing should match BackedEnum
exactly. I don't see the downside in doing this.
Example expected behavior:
<?php
declare(strict_types=1);
enum IntBacked: int {
case One = 1;
}
var_export(IntBacked::from(1)); // IntBacked::One
var_export(IntBacked::from('1')); // Fatal error: Uncaught ValueError: "1" is not a valid backing value for enum "IntBacked"
var_export(IntBacked::from('bogus')); // Fatal error: Uncaught ValueError: "bogus" is not a valid backing value for enum "IntBacked"
var_export(IntBacked::tryFrom(1)); // IntBacked::One
var_export(IntBacked::tryFrom('1')); // NULL
var_export(IntBacked::tryFrom('bogus')); // NULL
PHP Version
= 8.1.0
Operating System
No response