PHP Object could not be converted to int

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


class MyObject {
    protected $_id;
    public function setId($id) { $this->_id = $id; }
    public function __toString() { return $this->_id; }

$e = new MyObject();
if($e == "50") echo "50 == 50 as String\n";
else echo "50 !== 50 as String\n";

if($e == 50) echo "50 == 50 as Integer\n";
else echo "50 !== 50 as Integer\n";

if($e == 50) echo "50 == 50 as String = Integer\n";
else echo "50 !== 50 as String = Integer\n";

//The following statement just dies
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?

to a certain extend. __toString() is supposed to always return a string.

What you got is correct.

You write Object == String. PHP tries to invoke the ToString method of your class, and compares the result.
You write Object == Int. PHP has no idea how to render your object as an integer, so it throws a warning (and then probably assumes 0 for the comparison.)

The ‘proper’ way to do it if you wanted to keep it protected would be to write a getter for your ID, and compare that.

The only way to convert PHP object to integer is to install an integer/scalar expression addon/patch that do this for you from PHP RFC. You will need to have at least a VPS or even dedicated server to install a .diff patch file, which overwrites the default C code inside your PHP by what’s in the .diff file. Its for very advanced users, and aint recommended for beginners.

or you could just add a getter.

Yeah for now this is the only solution, although it sorta kills the purpose of object to int casting.