添加和连接时,PHP感到困惑 [英] PHP is confused when adding and concatenating
本文介绍了添加和连接时,PHP感到困惑的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有以下代码:
<?php
$a = 1;
$b = 2;
echo "sum: " . $a + $b;
echo "sum: " . ($a + $b);
?>
执行代码时,我得到:
2
sum: 3
为什么在第一个回显中无法打印字符串"sum:"
?将加号放在括号中似乎很好.
Why does it fail to print the string "sum:"
in the first echo? It seems to be fine when the addition is enclosed in parentheses.
这种奇怪的行为在任何地方都有记录吗?
Is this weird behaviour anywhere documented?
推荐答案
Both operators the addition +
operator and the concatenation .
operator have the same operator precedence, but since they are left associative they get evaluated like the following:
echo (("sum:" . $a) + $b);
echo ("sum:" . ($a + $b));
因此,您的第一行首先进行连接,最后以:
So your first line does the concatenation first and ends up with:
"sum: 1" + 2
(Now since this is a numeric context your string gets converted to an integer and thus you end up with 0 + 2
, which then gives you the result 2
.)
这篇关于添加和连接时,PHP感到困惑的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文