1

Here's a runnable example: https://onlinephp.io/c/d9c58

enum DigitEnum : int
{
    case TWO = 2;
}

$i = (int) DigitEnum::TWO; // emits a warning, expected

echo $i; // outputs 1

The output is:

Warning: Object of class DigitEnum could not be converted to int in /home/user/scripts/code.php on line 9
1

I understand the warning - I'm expecting that - but I don't understand the reasoning behind $i getting a value of 1. I mean as opposed to 0 or null or [NaN].

Reading https://www.php.net/manual/en/language.types.integer.php#language.types.integer.casting, there seems to be a precedent for "failed" conversions to result in 0, so that's probably what I'd expect?

I cannot find anything in the Enum documentation to explain why this might be a special case and is entirely legitimate. That's not to say it's not there somewhere, I just couldn't find it ;-)

Adam Cameron
  • 29,677
  • 4
  • 37
  • 78

1 Answers1

2

Enums are simply singleton objects. If you explicitly convert other class instances to int you also get 1 along with a warning.

You should use DigitEnum::TWO->value for the backed value.

According to: https://www.php.net/manual/en/function.intval.php

intval() should not be used on objects, as doing so will emit an E_NOTICE level error and return 1.

Dharman
  • 30,962
  • 25
  • 85
  • 135
  • It's fine, the rest is in the docs: https://www.php.net/manual/en/language.types.integer.php#language.types.integer.casting.from-other: "Caution The behaviour of converting to int is undefined for other types. Do not rely on any observed behaviour, as it can change without notice." – Adam Cameron Feb 12 '23 at 09:53
  • Haha, *of course* [slaps head, goes a bit red]. Thanks @Siu! Makes perfect sense. I even read the bit of the docs I include in my previous comment here, and didn't pay attn to it. Thanks again :-) – Adam Cameron Feb 12 '23 at 09:55