Can I close a file by unsetting the handle?

前端 未结 4 997
闹比i
闹比i 2020-12-18 06:47

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

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


        
4条回答
  •  挽巷
    挽巷 (楼主)
    2020-12-18 06:58

    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.

    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.

    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.


    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:

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

    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 :).


    Am searching the PHP source now for hard proof

提交回复
热议问题