Skip to content

Support Explicit Backed Enum casting #22288

@MircoBabin

Description

@MircoBabin

Description

The following code:

https://3v4l.org/pfXH4#v8.5.3

<?php

echo '----- Backed integer enum -----'.PHP_EOL;
enum DayOfWeekInt : int
{
    case Monday = 1;
    case Tuesday = 2;
    case Wednesday = 3;
    case Thursday = 4;
    case Friday = 5;
    case Saturday = 6;
    case Sunday = 7;
}
$var = DayOfWeekInt::Monday;

try {
    echo '--- intval($var) --'.PHP_EOL;
    echo intval($var);    
} catch (\Throwable $ex) {
    echo $ex;
}
echo PHP_EOL;

try {
    echo '--- (int) $var ---'.PHP_EOL;
    echo (int) $var;
} catch (\Throwable $ex) {
    echo $ex;
}
echo PHP_EOL;

echo PHP_EOL;
echo '----- Backed string enum -----'.PHP_EOL;
enum DayofWeekString : string
{
    case Monday = 'monday';
    case Tuesday = 'tuesday';
    case Wednesday = 'wednesday';
    case Thursday = 'thursday';
    case Friday = 'friday';
    case Saturday = 'saturday';
    case Sunday = 'sunday';
}
$var = DayofWeekString::Monday;

try {
    echo '--- strval($var) ---'.PHP_EOL;
    echo strval($var);
} catch (\Throwable $ex) {
    echo $ex;
}
echo PHP_EOL;
    
try {
    echo '--- (string) $var ---'.PHP_EOL;
    echo (string) $var;
} catch (\Throwable $ex) {
    echo $ex;
}
echo PHP_EOL;

Resulted in this output:

----- Backed integer enum -----
--- intval($var) --

Warning: Object of class DayOfWeekInt could not be converted to int in /in/pfXH4 on line 18
1
--- (int) $var ---

Warning: Object of class DayOfWeekInt could not be converted to int in /in/pfXH4 on line 26
1

----- Backed string enum -----
--- strval($var) ---
Error: Object of class DayofWeekString could not be converted to string in /in/pfXH4:48
Stack trace:
#0 {main}
--- (string) $var ---
Error: Object of class DayofWeekString could not be converted to string in /in/pfXH4:56
Stack trace:
#0 {main}

But I expected this output instead:

no warnings, no errors and a correct explicit conversion.

----- Backed integer enum -----
--- intval($var) --
1
--- (int) $var ---
1

----- Backed string enum -----
--- strval($var) ---
monday
--- (string) $var ---
monday

PHP Version

PHP 8.5.3

Operating System

No response

Metadata

Metadata

Assignees

No one assigned

    Type

    No type
    No fields configured for issues without a type.

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions