Skip to content

Using Enum object as array key? #150

Open
@TonyGravagno

Description

@TonyGravagno

Consider:

final class State extends Enum
{
   public const Activated = 'Activated'; ...
}

...
$obj->state[State::Activated] = true; 

Is this a mis-use of this mechanism? Should that be [State::Activated->value()] or even [State::Activated.''] ? With more housekeeping, the reason for using an Enum is diminished. Rather, I'm thinking that in languages that support enumerations this would present similar problems, so constants are preferred. In this case that means simply removing the extends Enum from any class that serves as a container for pure constants, where enums aren't really required.

Someone might ask why I'm using Enums rather than constants. It's for this technique to help eliminate bugs:

function get(State $settingID)
{
    switch ($settingID) {
       case State::Activated:
         return $this->state[State::Activated];
     ...
}

A development-time error is evident when calling get() without a valid spec. This is better than a production-time error (even switch/default) that might occur with an invalid constant value or even a string passed in. Unfortunately using Enum as above means the requests to get need to be:

$activated = $foo->get( State::Activated() ); // instance of Enum class

I don't mind that. The problem is that by "simply removing the extends Enum" as noted above, this also means all instantiation with parentheses State::Activated() need to be modified in the application as well. So much for "simple".

Yes, the get method can also do this:

function get($settingID)
{
    if($settingID instanceof State)
       $settingID = $settingID->value();
    else
       // string value, contant? literal? not as reliable

    switch ($settingID) {

We need to make decisions about how to handle all tools at our disposal. I'm not looking for some magic bullet, just guidance about we can and should use this Enum class. I suspect using Enum as an array key will break in PHP v8, so it's probably not a good idea to use it like this anyway. But the get( State::Activated() ) syntax is valid in any PHP version, so I'm looking for best short-term and long-term options.

The reason I'm asking about this is that it seems a shame to have an either/or choice, that it would be cool if we could use an Enum as an array key without the Enum actually being the key, but by default using the string value as the key in that specific context. So, I'm just documenting thoughts on this, for my immediate needs and in case someone else has similar thoughts.

Sincere thanks for this package. I've just started to use it and it's been very helpful ... when I don't abuse it 😉 .

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions