简体   繁体   English

PHP在添加和连接时感到困惑

[英]PHP is confused when adding and concatenating

I have the following code:我有以下代码:

<?php

    $a = 1;
    $b = 2;

    echo "sum: " .  $a + $b;
    echo "sum: " . ($a + $b);

?>

When I execute my code I get:当我执行我的代码时,我得到:

2
sum: 3

Why does it fail to print the string "sum:" in the first echo?为什么在第一个回显中无法打印字符串"sum:" 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 .) (现在因为这是一个数字上下文,你的字符串被转换为一个整数,因此你最终得到0 + 2 ,然后给你结果2 。)

If you look at the page listing PHP operator precedence , you'll see that the concatenation operator .如果您查看列出PHP 运算符优先级的页面,您会看到连接运算符. and the addition operator + have equal precedence, with left associativity.和加法运算符+具有相同的优先级,具有左结合性。 This means that the operations are done left to right, exactly as the code shows.这意味着操作是从左到右完成的,正如代码所示。 Let's look at that:让我们来看看:

$output = "sum: " . $a;
echo $output, "\n";
$output = $output + $b;
echo $output, "\n";

This gives the following output:这给出了以下输出:

sum: 1
2

The concatenation works, but you then try to add the string sum: 1 to the number 2 .连接有效,但您随后尝试将字符串sum: 1添加到数字2 Strings that don't start with a number evaluate to 0 , so this is equivalent to 0 + 2 , which results in 2 . 不以数字开头的字符串的计算结果为0 ,因此这等效于0 + 2 ,结果为2

The solution, as you suggest in your question, is to enclose the addition operations in brackets, so they are executed together, and then the result of those operations is concatenated.正如您在问题中所建议的那样,解决方案是将加法运算括在括号中,以便它们一起执行,然后连接这些运算的结果。

echo "sum: " . ($a + $b);

Since you use the language construct echo you can use a comma to separate the addition from the concatenation:由于您使用语言构造echo您可以使用逗号将添加与连接分开:

echo "sum: " , $a + $b;

Works as expected.按预期工作。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM