Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

__toString() should return value by default, not name #33

Closed
DmitryVarennikov opened this issue Mar 20, 2014 · 1 comment
Closed

__toString() should return value by default, not name #33

DmitryVarennikov opened this issue Mar 20, 2014 · 1 comment

Comments

@DmitryVarennikov
Copy link

I actually disagree that __toString() should return the name by default.

In JAVA enums "constants" can have NO value which is certainly invalid for PHP. And this is not the only difference. You can associate several values with a constant (and that's how usually enums are used in JAVA world). Regarding this it explains why things work this way in JAVA.

I believe for PHP we should adopt this structure and not just copy it blindly. The original argument stated by @prolic regarding usage of Enum in switch case is valid and I don't see any error. Moreover because we use constants in PHP to emulate enums I strongly expect to see a constant value casting Enum to string and not a constant name. This is expected and clear behaviour.

UPD: reference #24

@marc-mabe
Copy link
Owner

In JAVA enums "constants" can have NO value

That's not true. each enumeration has a value you can set it or leaf it but than Java takes the next integer value for you.

As already noted in #24:

  • __toString() have to return a string but constant values don't need to be strings which would result in a type-cast.
  • The values are unique using strict comparison. This could result in exactly the same strings for different values after type-cast.
  • The example switch statement isn't valid because:
    • It triggers notices Object of class MyIntEnum could not be converted to int
    • you simply should use the result of MyIntEnum::getValue() to init the switch statement else you get a big performance lost because PHP would automatically call the method and convert the value two time for each comparison

By the way __toString() is not final - you can overwrite it to return the value ;)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants