Pregunta

Do I need to close a file handle everytime I open a new file although I overwrite the file handle variable?

e.g.:

$fp = fopen("example.txt", 'w');
$fp = fopen("example.html", 'w');// is the file handle to example.txt closed now?
fclose($fp);

I'm creating several files inside of a loop and I think about if I need to close the handle for every file inside the loop or one time after the loop is finished.

¿Fue útil?

Solución

When the memory to the initial handle is released, your system may clean up the pointer and close it. With the following script:

$fp = fopen("example.txt", 'w');
$fp = fopen("example.html", 'w');

while (true);

I get the following output from inotifywait -m -r .:

MODIFY example.txt
OPEN example.txt
MODIFY example.html
OPEN example.html
CLOSE_WRITE,CLOSE example.txt

This means that without an explicit fclose on example.txt, it is being implicitly closed anyway by the Zend Engine, in the same way as it would close an open handle at the end of script execution (i.e. by reference-counting).

However, I would still recommend you properly and explicitly close any file handles, especially given your use case - the memory implications of opening multiple file handles in a loop should be enough of a concern here. Add to that any issues with long-running scripts potentially grabbing locks on files, security considerations, it's best to clean the handle properly.

See also: Why do I need fclose after writing to a file in PHP?

Otros consejos

The file handles will be still open until you call fclose()

All you do is overwrite variable, losing any reference to previous handle. If you still need to control them, assign them to different variables.

And garbage collectors usually must remove objects with no reference from memory, but that does not happen always.

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top