Loose typing not applied to objects
- by TecBrat
I have very little experience working with classes and object. I work in a loosely typed language, PHP.
I was working with a SimpleXML object and ran into a problem where I was trying to do math with an element of that object like $results->ProductDetail->{'Net'.$i};
If I echoed that value, I'd get 0.53 but when I tried to do math with it, it was converted to 0
Is there a reason that a loosely typed language would not recognize that as a float and handle it as such? Why would "echo" handle it as a string but the math fail to convert it?
Example:
$xml='<?xml version="1.0" encoding="UTF-8" ?>';
$xml.='<Test>
<Item>
<Price>0.53</Price>
</Item>
</Test>';
$result=simplexml_load_string($xml);
var_dump($result->Item->Price);
echo '<br>';
echo $result->Item->Price;
echo '<br>';
echo 1+$result->Item->Price;
echo '<br>';
echo 1+(float)$result->Item->Price;
Output:
object(SimpleXMLElement)#4 (1) { [0]=> string(4) "0.53" }
0.53
1
1.53