r/PHPhelp • u/mike_a_oc • Mar 11 '25
WeakMaps
I'm really curious about WeakMaps as they seem like a really interesting way of caching data, but when I asked ChatGPT about it, it always provided examples that paired the map with an associative array.
So I'm wondering, if I can't look up an object in theap by an arbitrary key, and I need to use an associative array, what is the value in WeakMap? Had anyone used it in an application? What was your use case?
0
Upvotes
5
u/Lumethys Mar 11 '25
Have you try to check different sources?
2
u/MateusAzevedo Mar 11 '25
From the docs:
It's a very specific use case, not suited for general caching of data. By the way, weak map keys are the object themselves, the idea is to map object to related/cached data. It isn't an
ID => objecttype of map.I must say that I personally never had a use case for them and I'm not sure how useful they commonly are. AFAIK, Doctrine uses it in its entity manager to keep a reference of entities fetched from the ORM, allowing for a few internal logic.
2
u/[deleted] Mar 12 '25
WeakMaps are a good for caching (e.g. store of data associated with an object; automatically garbage-collected when the object is destroyed), and for extending objects at runtime, particularly objects in third party libraries outside your control (a replacement for dynamically assigning properties at runtime, which was deprecated in PHP 8.2). As more and more people instrument PHP using RoadRunner, FrankenPHP, etc., memory considerations become more important, making the feature more useful.
Generally, though: they’re not something you’d reach for frequently, unless maybe you were writing a low-level framework or cache library. I’ve probably used them twice since the feature was introduced