php / php/php-src

Enum case as Array key?

Open
#9,208 56 comments 24 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

Feature Status: Requires RFC Status: Verified
Dominant language
C
Stars
40.4k
Forks
8.1k
Avg merge
2d 13h
Merged PRs (30d)
96

Description

Description

Before enum exist, i used constant to define the array key. Now i want to use enum. But i got error when i declare the enum as array key. so i do the workaround like this:

if (!function_exists('_api')) {
    /**
     * use enum as Array Key.
     *
     * @param array $values
     * @param \App\Enums\Api\ResponseKey $key
     * @param mixed $data
     * @return array
     */
    function _api(?array &$values, ResponseKey $key, $data)
    {
        if (! is_array($values)) $values = [];

        $values[$key->value] = $data;

        return $values;
    }
}

Then call it like _api($data, ResponseKey::message, "success");

Can this workaround can be implemented as feature for future PHP?

Contributor guide

Open the contributing guide

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

Research direction

No files or tests are named. Start by reading the issue discussion and reviewing PHP enum and array-key behavior, then locate the relevant language implementation and regression tests. Done would require an agreed language design and implementation with coverage for the intended enum-key behavior.

Written by the indexing model from the issue text.

Assessment

Tech stack
php
Domain
compilers
Issue type
Feature
Difficulty
5/5
Estimated time
Over a week
Activity status
Stale
Clarity
Mostly clear
Newbie friendliness
25/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.