为何在连接时必须在+-操作中添加括号? [英] Why do you have to add parentheses to + - operations when concatenating?

查看:74
本文介绍了为何在连接时必须在+-操作中添加括号?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

遇到奇怪的事情时,我正在写一个小程序. 如果我想让PHP用echo语句显示加法或减法的算术运算,而运算的结果则必须加上括号,否则html页面将不会给出运算,而只会给出结果.

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?

推荐答案

来自链接马克·贝克(Mark Ba​​ker)可以看到

from link by Mark Baker you can see that

加,减和字符串连接具有相同的优先级!

Addition, subtraction, and string concatenation have equal precedence!

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

连接第一个字符串文字和$a的值,然后将其隐式转换为数字(10),以便您可以向其中添加$b,然后连接最后一个字符串文字.

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.

当您将其放在方括号中时,加法将被视为number(15),因此不会对字符串进行任何数学运算

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

这篇关于为何在连接时必须在+-操作中添加括号?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆