首页 > 解决方案 > 为什么将字符串与未实现 __toString 的对象进行比较没有错误?

问题描述

我遇到了这样的问题。

<?php

class Foo
{
    public $f = 3;

//  public function __toString()
//  {
//      return 'test';
//  }
}

$foo = new Foo();

// do not implement __toString() -> PHP Recoverable fatal error:  Object of class Foo could not be converted to string
//$str = strval($foo);
//$str = (string)$foo;
//echo $foo . PHP_EOL;

// error not occurred... why?
if ($foo == "test") {
    echo 'hi';
}

if($foo == "test") 子句中发生了什么?

谢谢你的帮助。

标签: php

解决方案


推荐阅读