On Wed, Jul 10, 2024, at 19:48, Gina P. Banyard wrote:
> On Wednesday, 10 July 2024 at 18:34, Rob Landers <rob@bottled.codes> 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

Reply via email to