Does PHP close the file after the file handler is garbage collected?(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.
这篇关于PHP 是否在文件处理程序被垃圾收集后关闭文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:PHP 是否在文件处理程序被垃圾收集后关闭文件?


基础教程推荐
- HTTP 与 FTP 上传 2021-01-01
- PHP 守护进程/worker 环境 2022-01-01
- 如何在 Symfony 和 Doctrine 中实现多对多和一对多? 2022-01-01
- phpmyadmin 错误“#1062 - 密钥 1 的重复条目‘1’" 2022-01-01
- Doctrine 2 - 在多对多关系中记录更改 2022-01-01
- 如何在 XAMPP 上启用 mysqli? 2021-01-01
- 找不到类“AppHttpControllersDB",我也无法使用新模型 2022-01-01
- 使用 PDO 转义列名 2021-01-01
- 在 CakePHP 2.0 中使用 Html Helper 时未定义的变量 2021-01-01
- 在 yii2 中迁移时出现异常“找不到驱动程序" 2022-01-01