Php 为什么可以';SplFileInfo是否转换为布尔值?

Php 为什么可以';SplFileInfo是否转换为布尔值?,php,spl,truthiness,Php,Spl,Truthiness,PHP的一个限制是对象的计算结果总是true。但是SplFileinfo(以及子类,如Symfony的UploadedFile)的行为不同: $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'; // not

PHP的一个限制是对象的计算结果总是
true
。但是
SplFileinfo
(以及子类,如Symfony的
UploadedFile
)的行为不同:

$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

这是虫子吗?在5.3和5.4中测试。
SplFileObject
也会发生这种情况。可能的从2011年开始。

我觉得这是一个bug,所以我提交了一份bug报告


--编辑,大约在PHP5.6.17左右,这个错误似乎已经被修复

我也遇到了这个问题。我不知道对于这个异常PHP的rational是什么

对于其他遇到此问题的人,一个简单的解决方法就是将SplFileInfo对象与false进行比较

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

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

还有人认为这是一个特征;-)