Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

php

weakmap

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.

like image 673
Toskan Avatar asked Jan 26 '26 04:01

Toskan


1 Answers

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.

like image 143
shingo Avatar answered Jan 28 '26 17:01

shingo



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!