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

No object version:

$no='.53';
echo 1+$no;

Output:

1.53

================================

Side note: PHP strpos() does not properly convert an integer needle $i into a string.

$x=101; $i=1; if(strpos($x,"$i")===FALSE){echo $i." missing";}

and

$x=101; $i=1; if(strpos($x,$i)===FALSE){echo $i." missing";}

give different results. I don't want to become a php hater, but I'm beginning to lose that loving feeling.

有帮助吗?

解决方案

echo $result->Item->Price;

That will output a string variable.

echo 1+$result->Item->Price;

That will convert the string "0.53" to integer. PHP does not round up. So it becomes 0 and 1+0=1.

echo 1+(float)$result->Item->Price;

That works because you're telling PHP to cast to a float. PHP will then auto convert the 1 from an int to float.

Alternatively, you can also do this.

echo 1.0+$result->Item->Price;

That will tell PHP to convert the string to a float as well.

This is all part of PHP's type juggling.

http://us2.php.net/manual/en/language.types.type-juggling.php

Your issues are specific to string type conversion.

http://us2.php.net/manual/en/language.types.string.php#language.types.string.conversion

One of the reasons PHP can do these things is because the + operator is always mathematical. Where in other languages it performs string concatenation. Since + always performs addition PHP attempts to convert string types to numeric types to honor the + operation.

UPDATE: Problems specific to SimpleXMLElement

There is a known bug in PHP when using the extension SimpleXML. PHP will cast strings that represent float values to int instead of float. The automatic type juggling is not working correctly.

Here is a bug report for the issue: https://bugs.php.net/bug.php?id=54973

For now I recommend casting to (float) whenever you use SimpleXML and expect a float value. That should not break anything when the fix is pushed out in the future.

许可以下: CC-BY-SA归因
scroll top