Keyboard shortcuts

Press ← or → to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

Weakmap et enums

By Dmitri Goosens

<?php

enum WeekDay: string
{
    case Monday = 'monday';
    case Tuesday = 'tuesday';
    case Wednesday = 'wednesday';
    case Thursday = 'thursday';
    case Friday = 'friday';
    case Saturday = 'saturday';
    case Sunday = 'sunday';
}

class Foo
{
    public function hello()
    {
        return "Hello world" . PHP_EOL;
    }
}

$array = [];
$array[WeekDay::Monday->value] = new Foo();
// etc

echo $array[WeekDay::Monday->value]->hello();

$map = new WeakMap();
$map[WeekDay::Monday] = new Foo();
// etc

echo $map[WeekDay::Monday]->hello();

Un développeur PHP m’a rappelé qu’au lieu d’un simple tableau, on peut également utiliser WeakMap…

Ce qui est bien avec cela, c’est que c’est un vrai dictionnaire… qui accepte des objets comme clés… et cela inclut Enum::case.

See Also

PHP Features

Last updated: 11 October 2026