PHP5:SplObjectStorage 垃圾收集
我使用 SplObjectStorage 来保存有关托管对象的信息。当我的对象被破坏时,我希望 SplObjectStorage 能够自动清理不再有外部引用的对象。
我现在只能看到两个选项:
- 让托管对象的析构函数通知存储删除对其的引用;这是不可接受的,因为这些对象不应该知道管理器;
- 解析 debug_zval_dump() 以获取引用计数;也不可接受,恕我直言,对于严肃的应用程序来说太“hacky”了。
还有其他想法吗?
I'm using a SplObjectStorage to keep information about managed objects. When my objects get destructed, I would like the SplObjectStorage
to automatically cleanup the objects which have no external references anymore.
I can see only two options for this right now:
- having the managed object's destructor inform the storage to remove references to it; this is not acceptable as these objects should not be aware of the manager;
- parsing debug_zval_dump() to get the reference count; not acceptable as well, IMHO too "hacky" for a serious application.
Any other ideas?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
时间已经过去了& php 已经进化了,如果你在这里 &使用 php 8.2,还有另一个选择。
您可以使用 WeakMap 代替 SplObjectStorage
WeakMap
类似于splObjectStorage
从某种意义上说,它们都使用对象作为键。然而,WeakMap 并不能阻止在其他地方超出范围的对象被垃圾收集
对于上下文,这里是一个
splObjectStorage
示例:请注意,
$即使对象被取消设置,store
仍然拥有该对象...并且,这是一个
WeakMap
示例:请注意,
unsset
之后>'正在$object
、$store
计数为 0Time has gone by & php has evolved, if you are here & are using php 8.2, there is another option.
You can use a WeakMap instead of the SplObjectStorage
A
WeakMap
is similar to thesplObjectStorage
in the sense that they both use objects as keys.A WeakMap, however, does not prevent objects that fall out of scope everywhere else from being garbage collected
For context, here is an
splObjectStorage
example:Note that the
$store
still has the object even if the object was unsset...and, here is a
WeakMap
example:Note that after
unsset
'ing the$object
,$store
count is 0您可以尝试使用事件来实现所需的功能。每个托管对象都会在销毁时生成一个事件,并且对象管理器订阅该事件,因此它将能够从 SplObjectStorage 中删除对对象的引用。
You can try to implement desired functionality with events. Each managed objects generates an event on destroy and the object manager is subscribed on this event so it will be able to remove a reference to object from the SplObjectStorage.