Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
399 views
in Technique[技术] by (71.8m points)

php - Can I close a file by unsetting the handle?

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

Compared with:

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

... // script goes on for a long

Insights anyone?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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:

<?php

$db = mysql_connect(...);

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

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...