Why do you have to add parentheses to + - operations when concatenating?

試著忘記壹切 提交于 2019-12-23 10:48:09

问题


I was writing a small program when I encountered something strange. If I wanted PHP to present an arithmetic operations of addition or subtraction with an echo statement and the outcome of the operation I had to add parentheses or the html page wouldn't present the operation but just the outcome.

Below is a reduced example.

first case (without parentheses):

$a = 10;
$b = 5;
echo "$a + $b = ".$a + $b."<br>"; // 15
echo "$a - $b = ".$a - $b."<br>"; // 5
echo "$a * $b = ".$a * $b."<br>"; // 10 * 5 = 50
echo "$a / $b = ".$a / $b."<br>"; // 10 / 5 = 2
echo "$a % $b = ".$a % $b."<br>"; // 10 % 5 = 0

second case (with parentheses):

$a = 10;
$b = 5;
echo "$a + $b = ".($a + $b)."<br>"; // 10 + 5 = 15
echo "$a - $b = ".($a - $b)."<br>"; // 10 - 5 = 5
echo "$a * $b = ".($a * $b)."<br>"; // 10 * 5 = 50
echo "$a / $b = ".($a / $b)."<br>"; // 10 / 5 = 2
echo "$a % $b = ".($a % $b)."<br>"; // 10 % 5 = 0

Could anyone explain why this is happening?


回答1:


from link by Mark Baker you can see that

Addition, subtraction, and string concatenation have equal precedence!

in echo "$a + $b = ".$a + $b."<br>"; //15

Concatenate the first string literal and the value of $a, then implicitly convert that to a number (10) so you can add $b to it, then concatenate the final string literal.

when you put it in brackets, the addition is treated as number(15) therefore no mathematical operations with string



来源:https://stackoverflow.com/questions/35152105/why-do-you-have-to-add-parentheses-to-operations-when-concatenating

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!