PHP Object could not be converted to int

11.4k Views Asked by At

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?

3

There are 3 best solutions below

0
Jimmy On BEST ANSWER

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)
0
Tanase Butcaru On

One way of doing this better would be @bali182's solution by defining another method or you can cast object to string while comparing:

if((string)$e == something)

Either way, you'll have to change your code... *Tested on php 5.4.27

0
inf3rno On

There is no valueOf in PHP like we have in better languages and the interpreter is not good enough to try to convert to string and after that to other primitives. Maybe older versions supported that feature as you claim, I don't know. What you can do is (int) (string) $myObject or $myObject->toInt(). By comparison it is enough to covert to string, PHP will finish the rest if we are talking about loose equality.