Bug #65893 [Com]: cast to int/float always returns 1 for objects

From: Date: Mon, 14 Oct 2013 13:23:51 +0000
Subject: Bug #65893 [Com]: cast to int/float always returns 1 for objects
References: 1  Groups: php.bugs 
Request: Send a blank email to php-bugs+get-182147@lists.php.net to get a copy of this message
Edit report at https://bugs.php.net/bug.php?id=65893&edit=1 ID: 65893 Comment by: phpmpan at mpan dot pl Reported by: worldoffame at hotmail dot com Summary: cast to int/float always returns 1 for objects Status: Open Type: Bug Package: Class/Object related Operating System: Irrelevant PHP Version: Irrelevant Block user comment: N Private report: N New Comment: __toString serves mainly debugging purpose when one needs to output an object to the log easily or lookup its value fast during development. What's the purpose of casting an object to a number? Previous Comments: ------------------------------------------------------------------------ [2013-10-14 11:47:00] worldoffame at hotmail dot com Description: ------------ When I create an object with integer/float representation, Id expect that (int) and (float) casting will first convert the object using __toString(). This results in a numeric string, and they can then be cast into integers/floats. This does not seem to work at all as __toString() is not called when you cast objects to int/float. So instead I always get the number 1, a very annoying glitch I must say. Test script: --------------- // A number class abstract class Number extends Object{ protected $value; public function __toString(){ return (string)$this->value; } } class Integer extends Number{ public function __construct($value){ $this->value = (int)$value; } } class Float extends Number{ public function __construct($value){ $this->value = (float)$value; } } // Create integer and float objects $int = new Integer(3); $float = new Float(2.5); var_dump((int)$int); var_dump((float)$float); Expected result: ---------------- int(3) float(2.5) Actual result: -------------- int(1) float(1) ------------------------------------------------------------------------ -- Edit this bug report at https://bugs.php.net/bug.php?id=65893&edit=1

« previous php.bugs (#182147) next »