取消链接和 SplFileObject
是否可以取消文件与 SplFileObject 的链接?
我没有看到关闭底层资源的方法,并且文件句柄是私有的,因此无法以这一目标扩展 SplFileObject。
有什么解决方法吗?
Is it possible to unlink a file from an SplFileObject?
I don't see a method to close the underlying resource, and the file handle is private so one can't extend SplFileObject with that goal in mind.
Are there any workarounds?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我不推荐这样做,因为 PHP 会在幕后为您关闭文件。如果您看一下 php src,
ext/spl/spl_directory.c
:设置了一个处理程序,以便在所有引用耗尽时处理对象的清理。现在,我们检查清理处理程序:
spl_filesystem_object_free_storage
:php_stream_free
调用将为您关闭文件流。如果您取消链接该文件,我无法保证 PHP 将如何处理尝试关闭您刚刚链接的文件句柄。您必须记住 SplFileObject 为您提供的内容:
它为文件提供了许多基于迭代器的接口。如果您
取消链接
该文件,它应该迭代什么?您会注意到close()
也不存在于可用方法中。如果您想做您所说的事情,那么您最好将文件作为资源处理,您可以在其中close()
句柄并使其可通过unlink() 使用
,避免令人讨厌的副作用。I would not recommend this, because PHP closes the file behind scenes for you. If you take a look at the php src,
ext/spl/spl_directory.c
:A handler is setup in order to deal with the cleanup of the object when all references have been exhausted. Now, we check the cleanup handler:
spl_filesystem_object_free_storage
:The
php_stream_free
call will close the file stream for you. If you unlink the file, I can't guarantee how PHP will handle trying to close the file handle you just linked.You have to keep in mind what the SplFileObject provides you:
It's provides many iterator based interfaces for a file. If you
unlink
the file, what is it supposed to iterate over? You'll notice thatclose()
is not present in the available methods either. If you want to do what you're saying, then you're better off handling the file as a resource, where you canclose()
the handle and make it usable withunlink()
, saving from nasty side effects.