Re: [low priority] WeakMaps with scalar keys

From: Date: Wed, 10 Jul 2024 17:56:30 +0000
Subject: Re: [low priority] WeakMaps with scalar keys
References: 1 2  Groups: php.internals 
Request: Send a blank email to [email protected] to get a copy of this message
On Wed, Jul 10, 2024, at 19:48, Gina P. Banyard wrote:
> On Wednesday, 10 July 2024 at 18:34, Rob Landers <[email protected]> wrote:
>> Hello internals,
>> 
>> I know now that some of you are swamped getting ready for 8.4, so I want to be clear that
>> this will be an 8.5+ thing. I am simply sending it to the list in case anyone wants to discuss it,
>> burn it with fire, give it a gold star, or ignore until later.
>> 
>> Currently, a WeakMap may only have object keys, and this logically makes a lot of sense.
>> However, there are cases where you want to reference an object by a value but if the value is no
>> longer referenced, no longer need it. A good example of this might be used in dependency injection
>> containers, lookup tables for value objects, etc.
>> 
>> I'd like to propose a ReverseWeakMap where the keys must be scalar, and given an
>> object as the value. Once the value is no longer referenced, the key and value is removed from the
>> ReverseWeakMap.
> 
> Isn't this use case already solved with WeakReferences?
> https://www.php.net/manual/en/class.weakreference.php
> 
> 
> Best regards,
> 
> Gina P. Banyard
> 
>> 

Hey Gina,

The answer is: it depends. If you don’t need the array to clean up after itself, you can indeed
use an array of WeakReference to get most of the way there. If you want it to clean up after an
object gets removed, you either need to add support to the stored object’s destructor (which
isn’t always possible for built-in or final types), or create your own garbage collector that
scans the array. 

Now that I think about it, it might be simpler to add an “onRemove()” method that takes a
callback for the WeakReference class. 

— Rob


Thread (6 messages)

« previous php.internals (#124361) next »