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?
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?
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.
© 2022 - 2024 — McMap. All rights reserved.
SplFileObject::getPathName()
, unset theSplFileObject
(which I assume closes the handle) thenunlink
the path that you got. – Holarctic