Home » Php » php – Why can't SplFileInfo be converted to boolean?

php – Why can't SplFileInfo be converted to boolean?

Posted by: admin July 12, 2020 Leave a comment


One of the limitations of PHP is that objects always evaluate to true. However SplFileinfo (and subclasses such as Symfony’s UploadedFile) behave differently:

$a = new ArrayIterator();       // or any other class
$b = new SplFileInfo(__FILE__); // file used is not important

if ($a) echo 'true';   // 'true'
if (!$a) echo 'false'; // nothing because $a is true

if ($b) echo 'true';   // 'true'
if (!$b) echo 'false'; // Catchable fatal error: Object of class 
                       // SplFileInfo could not be converted to boolean

Is this a bug? Tested in 5.3 and 5.4. Also happens with SplFileObject. Possible related question. And a Symfony issue from 2011.

How to&Answers:

I feel it’s a bug so I filed a bug report.


— Edit, somewhere roughly around php 5.6.17 this bug seems to have been fixed.


I came across this issue as well. I don’t know what PHP’s rational for this exception is.

For anyone else coming across this, an easy workaround is just to compare the SplFileInfo object to false.

$b = new SplFileInfo(__FILE__);
if ($b != false) {
   echo "This will not throw an exception";

if (!$b) {
   echo "This will throw an exception";