文件处理程序被垃圾收集后,PHP是否关闭文件? [英] Does PHP close the file after the file handler is garbage collected?

查看:128
本文介绍了文件处理程序被垃圾收集后,PHP是否关闭文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

  function first_line($ file){
$ fh = fopen($ file);
$ first_line = fgets($ fh);
fclose($ fh);
返回$ first_line;



$ b $ p
$ b

可以简化为
$ b $函数first_line($文件){
返回fgets(fopen($文件)); $

  





$ b

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

解决方案

PHP一旦所有对该资源的引用都自动运行资源析构函数因为PHP有​​一个基于引用计数的垃圾回收机制,所以你可以相当确定这种情况会尽早发生,在你的情况下,只要<$ c $
$ b

在PHP 5.4之前 fclose didn'如果你试图关闭一个分配了两个以上引用的资源,实际上你可以做任何事。


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;
}

could then be simplified to

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 automatically runs the resource destructor as soon as all references to that resource are dropped.

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.

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是否关闭文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆