PHP is confused when adding and concatenating(PHP在添加和连接时感到困惑)
问题描述
我有以下代码:
<?php
$a = 1;
$b = 2;
echo "sum: " . $a + $b;
echo "sum: " . ($a + $b);
?>
当我执行我的代码时,我得到:
When I execute my code I get:
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
(现在因为这是一个数字上下文,你的 字符串被转换为整数,因此你最终得到0 + 2
,然后得到结果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在添加和连接时感到困惑的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:PHP在添加和连接时感到困惑


基础教程推荐
- 将变量从树枝传递给 js 2022-01-01
- 主题化 Drupal 7 的 Ubercart “/cart"页 2021-01-01
- PHPUnit 的 Selenium 2 文档到底在哪里? 2022-01-01
- 如何在数学上评估像“2-1"这样的字符串?产生“1"? 2022-01-01
- Web 服务器如何处理请求? 2021-01-01
- php中的foreach复选框POST 2021-01-01
- 使用 scandir() 在目录中查找文件夹 (PHP) 2022-01-01
- php中的PDF导出 2022-01-01
- php 7.4 在写入变量中的 Twig 问题 2022-01-01
- Yii2 - 在运行时设置邮件传输参数 2022-01-01