Unlink and SplFileObject

て烟熏妆下的殇ゞ 提交于 2019-12-13 13:03:41

问题


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?


回答1:


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:

retval.handle = zend_objects_store_put(intern, 
  (zend_objects_store_dtor_t) zend_objects_destroy_object, 
  (zend_objects_free_object_storage_t) spl_filesystem_object_free_storage, 
   NULL TSRMLS_CC);

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:

    case SPL_FS_FILE:
        if (intern->u.file.stream) {
            if (intern->u.file.zcontext) {
/*              zend_list_delref(Z_RESVAL_P(intern->zcontext));*/
            }
            if (!intern->u.file.stream->is_persistent) {
                php_stream_free(intern->u.file.stream, PHP_STREAM_FREE_CLOSE);
            } else {
                php_stream_free(intern->u.file.stream, PHP_STREAM_FREE_CLOSE_PERSISTENT);
            }
            if (intern->u.file.open_mode) {
                efree(intern->u.file.open_mode);
            }
            if (intern->orig_path) {
                efree(intern->orig_path);
            }
        }
        spl_filesystem_file_free_line(intern TSRMLS_CC);
        break;

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:

SplFileObject extends SplFileInfo implements RecursiveIterator , Traversable , Iterator , SeekableIterator {

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 that close() 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 can close() the handle and make it usable with unlink(), saving from nasty side effects.



来源:https://stackoverflow.com/questions/6066145/unlink-and-splfileobject

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!