If fclose closes a file, how do you close an open file with the Splfileobject object?

Asked

Viewed 89 times

3

When we open a file with fopen, we use the function fclose to close the file handler.

 $handle = fopen('file.txt', 'r');

 fclose($handle);

But my curiosity is: And when we use the object SplFileObject? He doesn’t have the method fclose.

How the file is closed when we instantiate this class to open it?

$file = new SplFileObject('file.txt', 'r');

$file-> // Como faço para fechar?

1 answer

4


Just set it to null

$file = new SplFileObject('file.txt', 'r');

$file = null;

In general objects has a Cleanup in the destructor, the fact of setting the variable to null already does what is needed in many cases. And even without destructor, the GC collects the resources normally, at some point (attention, read to the end).

Note that this does not necessarily apply to any class. To be sure, you need to see the documentation for the specific class, or analyze the implementation if you have access to sources.

Including, according to a comment in the manual, by having an undocumented private property that holds the file Pointer, the files are locked into the object’s existence.

http://php.net/manual/en/class.splfileobject.php#113149

  • 1

    +1 interesting, so it works the same way as in PDO. Cool

Browser other questions tagged

You are not signed in. Login or sign up in order to post.