問題描述
如果我有一個打開文件并讀取一行的簡短函數,我是否需要關閉文件?或者當執行退出函數并且 $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 是否在文件處理程序被垃圾收集后關閉文件?的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!