如果我有一个打开文件并读取一行的短函数,我是否需要关闭该文件?或者,当执行退出函数并且$fh垃圾收集时,PHP会自动执行此操作吗?
function first_line($file) {
$fh = fopen($file);
$first_line = fgets($fh);
fclose($fh);
return $first_line;
}
Run Code Online (Sandbox Code Playgroud)
然后可以简化为
function first_line($file) {
return fgets(fopen($file));
}
Run Code Online (Sandbox Code Playgroud)
这当然是理论上的,因为这段代码没有任何错误处理.
Nik*_*kiC 14
只要删除了对该资源的所有引用,PHP就会自动运行资源析构函数.
由于PHP具有基于引用计数的垃圾收集,因此您可以相当确定这种情况会尽快发生,在您的情况下,一旦 $fh超出范围.
在PHP 5.4之前,fclose如果您尝试关闭分配了两个以上引用的资源,则实际上没有做任何事情.
cle*_*ong 12
是.资源超出范围时会自动释放.以机智:
<?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();
?>
Run Code Online (Sandbox Code Playgroud)
输出:
before open
open dummy://hello
close
after open
Run Code Online (Sandbox Code Playgroud)
fopen()返回后立即释放文件句柄,因为此处没有捕获句柄的内容.
| 归档时间: |
|
| 查看次数: |
4549 次 |
| 最近记录: |