How to close a SplFileObject file handler?

Gilles picture Gilles · Mar 17, 2014 · Viewed 7.9k times · Source

I'm working with files in PHP using SplFileInfo and SplFileObject. But when I try to "re-open" a file, it yells me :

 SplFileObject::__construct(filemame): failed to open stream: Permission denied

I think I should close my file before re-opening it, but I can't figures how. SplFile* have no close function ?!

Answer

zkanoca picture zkanoca · Apr 2, 2014

You should set SplFileObject to null in order to close the file.

<?php

     $fileHandler = new SplFileObject('file.name');
     //now file.name is open

     $fileHandler = null;
     //file.name is closed.

     $fileHandler2 = new SplFileObject('file.name');
     //file.name is re-opened

?>