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 是否在文件处理程序被垃圾收集后关闭文件?
基础教程推荐
- Cron Jobs 调用带有变量的 PHP 脚本 2022-01-01
- PHP PDO MySQL 查询 LIKE ->多个关键词 2021-01-01
- 如何在 Laravel 中使用 React Router? 2022-01-01
- 如何替换eregi() 2022-01-01
- YouTube API v3 点赞视频,但计数器不增加 2022-01-01
- PHP 类:全局变量作为类中的属性 2021-01-01
- 如何在 Laravel 5.3 注册中添加动态下拉列表列? 2021-01-01
- 在PHP中根据W3C规范Unicode 2022-01-01
- 学说 dbal querybuilder 作为准备好的语句 2022-01-01
- 有什么方法可以用编码 UTF-8 而不是 Unicode 返回 PHP`json_encode`? 2021-01-01
