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

Public const inside Enum class #157

Open
enotocode opened this issue Oct 20, 2021 · 1 comment
Open

Public const inside Enum class #157

enotocode opened this issue Oct 20, 2021 · 1 comment

Comments

@enotocode
Copy link

enotocode commented Oct 20, 2021

Hi,
there is an example in the readme.md of Enum class with private constant. Why it uses private const instead of public const?

Public modifier makes it possible to use class constant in array property:

final class Action extends Enum
{
    public const VIEW = 'view';
    public const EDIT = 'edit';
}

class ActionValidation 
{
    private array types = [Action::VIEW, Action::EDIT];
}
@drealecs
Copy link
Contributor

drealecs commented Dec 7, 2021

Hey @enotocode,
Using private constants is recommended as it makes it harder to directly use a value of a case in the code and more use the instance of the enum.
The value $value = $action->getValue()should only be used when serializing the enum instance for transmission to something else than the PHP runtime: http request, sql value for storing in database, cached value. For restoring the $action = Action::from($value) should be used in the communication layer, as close as possible after you receiving it.
This is also inline with how the enum in PHP 8.1 is designed and used.
In my experience, I've seen improper use of Enums using this package and using private constant would have enforced this.
There are cases where a class/interface contains just a list of constants without being an enum. For example: https://github.com/php-fig/http-message-util/blob/master/src/RequestMethodInterface.php
For that case, just not use an enum would be the recommendation from me.

For you example, I think that instead if building an array of possible values for Action and check with in_array if the incoming action is present in it, you can use Action::isValid()/Action::assertValidValue() or, even better, directly Action::from() and use further the obtained instance that you know from this point is valid.

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