我刚刚从 PHP 5.3 升级到 PHP 5.5,并且在使用 __toString() 方法将 Object 转换为 int 时遇到了以前没有得到的警告。
示例代码是
<?php
class MyObject {
protected $_id;
public function setId($id) { $this->_id = $id; }
public function __toString() { return (string)$this->_id; }
}
$e = new MyObject();
$e->setId("50");
if($e == "50") echo "50 == 50 as String\n";
else echo "50 !== 50 as String\n";
$e->setId(50);
if($e == 50) echo "50 == 50 as Integer\n";
else echo "50 !== 50 as Integer\n";
$e->setId("50");
if($e == 50) echo "50 == 50 as String = Integer\n";
else echo "50 !== 50 as String = Integer\n";
$e->setId(50);
if($e == "50") echo "50 == 50 as Integer = String\n";
else echo "50 !== 50 as Integer = String\n";
我服务器中的输出是
50 == 50 as String
50 !== 50 as Integer
50 !== 50 as String = Integer
50 == 50 as Integer = String
虽然我期待它们都是真实的。我在运行它时收到的通知是:
Object of class MyObject could not be converted to int
它们由包含代码的行触发
($e == 50)
这是故意的吗?我可以在 PHP ini 中设置任何变量以使其以不同的方式工作吗?我是否只需要学习处理它并查看我所有可能在某些代码中使用 Objects as Integers 的代码?