如果我有一个打开文件并读取一行的简短函数,我是否需要关闭文件?或者当执行退出函数并且 $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模板网!
PHP、MySQL PDOException 的死锁异常代码?Deadlock exception code for PHP, MySQL PDOException?(PHP、MySQL PDOException 的死锁异常代码?)
PHP PDO MySQL 可滚动游标不起作用PHP PDO MySQL scrollable cursor doesn#39;t work(PHP PDO MySQL 可滚动游标不起作用)
PHP PDO ODBC 连接PHP PDO ODBC connection(PHP PDO ODBC 连接)
使用 PDO::FETCH_CLASS 和魔术方法Using PDO::FETCH_CLASS with Magic Methods(使用 PDO::FETCH_CLASS 和魔术方法)
php pdo 只从 mysql 获取一个值;等于变量的值php pdo get only one value from mysql; value that equals to variable(php pdo 只从 mysql 获取一个值;等于变量的值)
MSSQL PDO 找不到驱动程序MSSQL PDO could not find driver(MSSQL PDO 找不到驱动程序)