phpweakmap

Php's "new" WeakMap - do Enums ever get garbage collected?


https://www.php.net/manual/en/class.weakmap.php

what about Enums?

You can do

enum MyEnum{
case A;
}
$wm = new WeakMap();
$wm[MyEnum::A] = 'something';

when does

$wm[MyEnum::A] become invisible? or inaccessible? if ever?

I am NOT talking about $wm. Assume $wm is always there.


Solution

  • An enum in php is just a (special) class with several constants, this is simple to verify:

    enum MyEnum { case A; }
    
    // enum(MyEnum::A)
    // string(6) "object"
    var_dump(  
        (new ReflectionClass(MyEnum::class))->getConstant('A'),
        gettype(MyEnum::A));
    

    Because no one can unset a constant or change its value, there is at least one reference to the enum object, the entry in the WeakMap will remain until someone manually unsets it.