SPL stands for Standard PHP Library.
SplFileObject
uses internally the stream resource created with fopen
. So your question should be when is it interesting to uses SplFileObject
or to directly work with a stream resource ?
SplFileObject
pros:
SplFileObject
provide an OOP approach to file manipulation (fread
was added in PHP 5.5.11, fputcsv
was added in PHP 5.4).
SplFileObject
implements several useful PHP Interfaces to enable the use of other SPL Iterator to better manipulate your file.
SplFileObject
main disadvantage is that it does not give access to its
internal stream resource. PHP functions were originally build to directly work with a stream resource. The fact that the SplFileObject
does not give access to its own internal stream resource make it unusable with many PHP built in functions:
php stream filters usage is poor with SplFileObject
. You need to relies on the php://filter
meta wrapper, which limits their usefulness.
using SplFileObject
with cURL
is not possible
To sum it up SplFileObject
and a stream resource are not interchangeable. Anything done using SplFileObject
could be achieved using a stream resource and a SplFileObject
userland implementation but the reverse is not true.
So depending on the use case using a stream resource created by fopen
can be a better choice than relying on SplFileObject
.
As for the close method, you don't need one... you just need to set the handler to null to release/close the internal stream resource.
$file = new SplFileObject('/path/to/my/file'); //the file handler is created
$file = null; //the file handler is closed