Does PHP close the file after the file handler is garbage collected?
file-io, php
Solution
PHP automatically runs the resource destructor as soon as all references to that resource are dropped.
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.
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.
Problem
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; } ``` could then be simplified to ``` function first_line($file) { return fgets(fopen($file)); } ``` This is of course theoretical right now, as this code doesn't have any error handling.