SimpleXML weird styling behavior

Today one of our customers sent a complaint that in his store some prices are slightly lower (1, - Kč for sure). When I started debugging, I thought it might be a rounding error. We use SimpleXML to import product prices and from the look of the code, everything seemed correct, but when I made the var_dumps cube, some prices were very poorly rounded. There is a ceiling function that supports a ceiling of 54.6200 to 54 . I understand that before using them, I must give all the SimpleXML values, but this behavior seemed rather strange to me. It looks like when I overlap the floating point value stored in the node string of the SimpleXMLElement element, the value is assigned to the int method before the ceil function.

It’s good that with something I can live with, the script was programmed by someone who probably didn’t know that he needed to get everything out of SimpleXML, but that still seems a little strange to me. Does anyone know how this happens? PHP ceil function acceps float as an argument, so I expect the value to get typecasted for float, but in this case it is int. (you can run the code)

 <?php $item = simplexml_load_string( <<<ITEM <Item> <PHE>54.6200</PHE> </Item> ITEM ); echo '<pre>'; echo $item->PHE.PHP_EOL; //54.6200 echo ceil($item->PHE).PHP_EOL; //54!!! echo ceil((string)$item->PHE).PHP_EOL; //55 echo ceil((float)$item->PHE).PHP_EOL; //55 echo ceil('54.6200'); //55 echo PHP_EOL.PHP_EOL; debug_zval_dump($item); echo '</pre>'; 

The output of this zval_dump:

 object(SimpleXMLElement)#1 (1) refcount(2){ ["PHE"]=> string(7) "54.6200" refcount(1) } 
+4
source share
1 answer

PHP usually prefers to convert an object to an integer in the context of a mathematical operation. Say what you do:

 $obj = new InternalClass(); var_dump(5 + $obj); 

The implementation of this operator sees the object and must decide what to do with it. Internal objects are equipped with a hook, which allows you to convert them to any type ( cast_object ). However, this handler receives only one type of target. The engine must decide what type to convert the object to before doing this, and unfortunately, it selects an integer type.

Your only option is to add an explicit cast, just like you.

+2
source

All Articles