Why can't SplFileInfo be converted to boolean?
Asked Answered
I

2

7

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.

Interrupter answered 5/7, 2013 at 12:14 Comment(0)
L
7

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

https://bugs.php.net/bug.php?id=65213

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

Landloper answered 8/7, 2013 at 2:19 Comment(1)
And someone else thinks it's a feature ;-)Interrupter
C
4

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";
}
Capacious answered 27/8, 2014 at 5:55 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.