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.
The fclose() function closes an open file pointer. Note: The file must have been opened by fopen() or fsockopen().
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.
Yes. Resources are released automatically when they go out of scope. To wit:
<?php class DummyStream { function stream_open($path, $mode, $options, &$opened_path) { echo "open $path<br>"; return true; } function stream_close() { echo "close<br>"; return true; } } stream_wrapper_register("dummy", "DummyStream"); function test() { echo "before open<br>"; fopen("dummy://hello", "rb"); echo "after open<br>"; } test(); ?>
Output:
before open open dummy://hello close after open
The file handle is released as soon as fopen() returns, as there's nothing here capturing the handle.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With