PHP 是否在文件处理程序被垃圾收集后关闭文件?

2021-12-29 00:00:00 file-io php

如果我有一个打开文件并读取一行的简短函数,我是否需要关闭文件?或者当执行退出函数并且 $fh 被垃圾收集时,PHP 会自动执行此操作吗?

If I have a short function that opens a file and reads a line, do I need to close the file? Or will PHP do this automatically when execution exits the function and $fh is garbage collected?

function first_line($file) {
    $fh = fopen($file);
    $first_line = fgets($fh);
    fclose($fh);
    return $first_line;
}

可以简化为

function first_line($file) {
    return fgets(fopen($file));
}

这当然是理论上的,因为这段代码没有任何错误处理.

This is of course theoretical right now, as this code doesn't have any error handling.

推荐答案

一旦对资源的所有引用都被删除,PHP 就会自动运行资源析构函数.

PHP automatically runs the resource destructor as soon as all references to that resource are dropped.

由于 PHP 具有基于引用计数的垃圾收集,因此您可以相当确定这会尽早发生,在您的情况下,一旦 $fh 超出范围.

As PHP has a reference-counting based garbage collection you can be fairly sure that this happens as early as possible, in your case as soon as $fh goes out of scope.

在 PHP 5.4 之前 fclose 如果您试图关闭分配了两个以上引用的资源,实际上并没有做任何事情.

Before PHP 5.4 fclose didn't actually do anything if you tried to close a resource that had more than two references assigned to it.

相关文章