可以通过取消手柄关闭文件吗? [英] Can I close a file by unsetting the handle?

查看:105
本文介绍了可以通过取消手柄关闭文件吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果仅通过取消带有句柄的变量就可以保留fclose命令,我会感到困惑吗?

I'm a little puzzled if I can spare the fclose command by just unsetting the variable that carries the handle?

$handle = fopen($file);
...
fclose($handle);

... // script goes on for a long

与之比较:

$handle = fopen($file);
...
unset($handle);

... // script goes on for a long

有见识的人吗?

推荐答案

由于PHP 4的Zend Engine引入了引用计数系统,因此将自动检测到没有更多引用的资源,并由垃圾收集器将其释放.

Thanks to the reference-counting system introduced with PHP 4's Zend Engine, a resource with no more references to it is detected automatically, and it is freed by the garbage collector.

考虑这一点的含义.可以肯定地认为,变量的所有痕迹在垃圾回收之后都消失了.换句话说,在PHP执行结束时,如果PHP仍未跟踪引用,它将如何关闭它?因此,在垃圾收集器吃掉它时将其关闭似乎是很合逻辑的.

Consider the implications of this. It's safe to assume that all traces of the variable are gone after the garbage collection. In other words, at the end of PHP's execution, if PHP is not still tracking the reference, how would it close it? Thus, it seems fairly logical that it would close it when the garbage collector eats it.

这是一个错误的逻辑论点,因为它假定垃圾回收会立即发生或在取消设置后立即发生,并且PHP不会保留对用户域中不再存在的变量的隐藏引用.

This is a bad logical argument though because it assumes that garbage collections happens either immediately or shortly after unset and that PHP does not keep hidden references to variables that no longer exist in user land.

如果PHP在超出范围时不关闭文件句柄,则更令人信服的情况可能是潜在的行为缺陷.考虑某种可以打开大量文件的守护程序.现在考虑是否从未调用过fclose.取而代之的是,允许变量超出范围或对变量进行显式调用.

A more compelling case though could be a potential behavioural flaw if PHP did not close file handles when they go out of scope. Consider a daemon of some kind that opens lots of files. Now consider if fclose is never called. Instead, variables are allowed to fall out of scope or unset is explicitly called on them.

如果未关闭这些文件句柄,则此运行时间较长的守护程序将用完文件句柄.

If these file handles were not closed, this long running daemon would run out of file handles.

特定于行为的测试脚本:

Potentially behavior specific test script:

<?php

$db = mysql_connect(...);

if ($db) {
    echo "Connected\n";
    sleep(5); //netstat during this just for paranoia
    unset($db);
    echo "Unset\n";
    sleep(5); //netstat during this and the connection is closed
}

在Windows 7和Debian 6上,取消设置后,连接均已关闭.

On both Windows 7 and Debian 6, the connection has been closed after the unset.

但是,显然,这仅证明在具有特定PHP版本的特定计算机上可以正常工作.对文件句柄等没有任何意义:).

Obviously though, this only proves that on my specific machines with my specific PHP version will this work. Has no meaning on file handles or the like :).

现在正在搜索PHP源代码以获取可靠证据

这篇关于可以通过取消手柄关闭文件吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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