字符串连接与 echo

你可以在输出字符串时使用串联来 端到端 连接字符串 (例如,使用 echoprint)。

你可以使用 .(句点/点)连接变量。

// String variable
$name = 'Joel';

// Concatenate multiple strings (3 in this example) into one and echo it once done.
//      1. ↓        2. ↓            3. ↓    - Three Individual string items
echo '<p>Hello ' . $name . ', Nice to see you.</p>';
//               ↑       ↑                  - Concatenation Operators

#> "<p>Hello Joel, Nice to see you.</p>"

与连接类似,echo(在没有括号的情况下使用时)可以用于使用逗号(, )将字符串和变量(以及其他任意表达式)组合在一起。

$itemCount = 1;

echo 'You have ordered ', $itemCount, ' item', $itemCount === 1 ? '' : 's';
//                      ↑           ↑        ↑                - Note the commas

#> "You have ordered 1 item"

字符串连接与将多个参数传递给 echo

在某些情况下,将多个参数传递给 echo 命令比字符串连接更有利。参数以与传入的顺序相同的顺序写入输出。

echo "The total is: ", $x + $y;

连接的问题是时间段 . 优先于表达式。如果连接,上面的表达式需要额外的括号来表示正确的行为。这个时期的优先权也会影响三元运算符。

echo "The total is: " . ($x + $y);