Object of class %s could not be converted to int

Description

PHP reports that the object cannot be used as an integer. Converting an object into a int is only possible when the underlying class has provided the code for it. There is no userland code to do that, such as a magic code: it is only possible via a call to a method that returns an integer.

Among the PHP classes, gmp and bcmath (in PHP 8.4) extensions provide classes which also works with math operations. Most of the other classes do not convert easily to numbers, as it makes little sense to convert a database connexion (for example) into a number.

Example

<?php

class Y { }

// Error!
echo new Y + 1;

$multiplication = gmp_mul('12', 3);

print $multiplication * 4; // 144

$number = new BcMath\Number('1.234');

$addition = $number->add(new BcMath\Number('2.34567'));

print $addition + 1; // 4.57967

?>

Literal Examples

  • Object of class Y could not be converted to int

  • Object of class Datetime could not be converted to int

Solutions

  • Implement tod that returns an integer, on that object.

  • Upgrade to PHP 8.4, to use automatic conversion with bcmath.