php-enum icon indicating copy to clipboard operation
php-enum copied to clipboard

Public const inside Enum class

Open enotocode opened this issue 3 years ago • 1 comments

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];
}

enotocode avatar Oct 20 '21 14:10 enotocode

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.

drealecs avatar Dec 07 '21 15:12 drealecs