|
php.net | support | documentation | report a bug | advanced search | search howto | statistics | random bug | login |
[2010-10-10 00:45 UTC] rowan dot collins at gmail dot com
Description: ------------ When an object defined by an extension, such as SimpleXML, is used in a mathematical context, it is always converted to an int, never a float. This is inconsistent with the behaviour of other data types, which are automatically treated as a float if appropriate [e.g. the string "2.5" used in mathematical context is not truncated to int(2)]. This is impossible with user-defined classes, since no magic methods are available for governing cast to float or int, but binary object definitions can control this behaviour. This results in highly undesirable behaviour with SimpleXML objects, as reported in #42780 I have searched previous bug reports and the documentation, but cannot see any justification or documentation regarding this behaviour. In particular, there is no mention at http://php.net/manual/en/language.types.type-juggling.php or http://www.php.net/manual/en/language.types.object.php#language.types.object.casting and the tables at http://www.php.net/manual/en/types.comparisons.php do not cover implicit casts of this type. Test script: --------------- <?php $x = simplexml_load_string('<x>2.5</x>'); var_dump($x*1); // int(2) // type of other operand is irrelevant var_dump($x*1.0); // float(2) // strings behave differently $y = '2.5'; var_dump($y*1); // float(2.5) var_dump((string)$x*1); // float(2.5) ?> Expected result: ---------------- All 4 examples should result in float(2.5) Actual result: -------------- As commented above. Unless the object is cast to string first, it is processed as an int, not a float, and the .5 is discarded. PatchesPull RequestsHistoryAllCommentsChangesGit/SVN commits
|
|||||||||||||||||||||||||||||||||
Copyright © 2001-2025 The PHP GroupAll rights reserved. |
Last updated: Sun Oct 26 19:00:01 2025 UTC |
read: (...) and PHP prefers a int (not a double). By the way, the work-around is to ask for a double conversion explicitly: <?php $x = simplexml_load_string('<x>2.5</x>'); var_dump((double)$x*1); // float(2.5)