如果我有一个打开文件并读取一行的短函数,我需要关闭该文件吗?或者,当执行退出函数并且$fh
被垃圾回收时,PHP会自动执行此操作吗?
function first_line($file) {
$fh = fopen($file);
$first_line = fgets($fh);
fclose($fh);
return $first_line;
}
然后可以简化为
function first_line($file) {
return fgets(fopen($file));
}
这当然是理论上的,因为这段代码没有任何错误处理。
PHP在删除对资源的所有引用后立即自动运行资源析构函数。
由于PHP有一个基于引用计数的垃圾收集,所以您可以非常确定,一旦$fh
超出范围,这种情况就会尽早发生。
在PHP 5.4之前,如果您试图关闭一个分配了两个以上引用的资源,fclose
实际上不会做任何事情
是。资源超出范围时会自动释放。也就是说:
<?php
class DummyStream {
function stream_open($path, $mode, $options, &$opened_path) {
echo "open $path<br>";
return true;
}
function stream_close() {
echo "close<br>";
return true;
}
}
stream_wrapper_register("dummy", "DummyStream");
function test() {
echo "before open<br>";
fopen("dummy://hello", "rb");
echo "after open<br>";
}
test();
?>
输出:
before open
open dummy://hello
close
after open
一旦fopen()返回,文件句柄就会被释放,因为这里没有捕获句柄的内容。
是的,但最好在完成文件指针后立即关闭它们。这样,如果您有另一个应用程序需要对该文件进行写访问,它就可以正常运行。
需要研究的是PHP 5.3及更好版本中的垃圾回收功能。