Search code examples
phpphp-5.5object-to-string

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

<?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";

The output in my server is

50 == 50 as String
50 !== 50 as Integer
50 !== 50 as String = Integer
50 == 50 as Integer = String

While I was expecting all of them to be true. The notices I get while running it are:

Object of class MyObject could not be converted to int

They are triggered by the lines that contain the code

($e == 50)

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?


Solution

  • I'm going to answer my question by quoting Sammitch's comment

    You wrote some code that relies on abusing some ill-defined typing and conversion shenanigans in PHP, we've all done it at some point. PHP devs have fixed that and broken your code. The solution is to fix your code and learn a lesson about abusing PHP's loose typing system.

    The fix was to review our code and change the code lines to either

    if("$e" == 50)
    

    or

    if($e->getId() == 50)