I just upgraded from PHP 5.3 to PHP 5.5 and I’m facing a warning that I didn’t get before when casting an Object to a int using the __toString() method.
The sample code is
<?php
class MyObject {
protected $_id;
public function setId($id) { $this->_id = $id; }
public function __toString() { return $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";
//The following statement just dies
$e->setId(50);
if($e == "50") echo "50 == 50 as Integer = String\n";
else echo "50 !== 50 as Integer = String\n";
The output in my server is
50 == 50 as String
50 !== 50 as Integer
50 !== 50 as String = Integer
While I was expecting all of them to be true. The notice I get while running it is:
Object of class MyObject could not be converted to int
It’s this intended? Is there any variable I can set in the PHP ini to make it work differently? Do I just need to learn to deal with it and review all my code that may use Objects as Integers in some codes?