Adam Cameron
Adam Cameron

Reputation: 29870

Enum explicit cast to int returns 1 (and warning)

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 ;-)

Upvotes: 1

Views: 1257

Answers (1)

Siu Pang Tommy Choi
Siu Pang Tommy Choi

Reputation: 475

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.

Upvotes: 4

Related Questions