简体   繁体   English

PHP在带有花括号的字符串中嵌入数组元素

[英]PHP embedding array element inside string with curly braces

I would like to know what the advantage of using curly braces is in the following context: 我想知道在以下上下文中使用花括号的优点是什么:

$world["foo"] = "Foo World!";
echo "Hello, {$world["foo"]}.\n";

is over the following: 超过以下:

$world["foo"] = "Foo World!";
echo "Hello, $world["foo"].\n";

In particular, how is it that the braces resolve any possible ambiguity in this case (or similar cases)? 特别是,在这种情况下(或类似情况),大括号如何解决任何可能的歧义?

Second example will not be parsed. 第二个例子不会被解析。 So first is better:) 所以首先是更好的:)

Anyway, I prefer to use 无论如何,我更喜欢使用

echo "Hello" . $world["foo"] . ".\n";

Because it is more easy to read to me. 因为它更容易给我读。

Besides, there is another way: 此外,还有另一种方式:

$world["foo"] = "Foo World!";
echo "Hello, $world[foo].\n";

There no resaons to use one or another. 没有任何反复使用这一个或另一个。 you what you(or your team) like. 你是你(或你的团队)喜欢什么。

See the other answers for the "echo" explanation, but if you're using heredoc, such as the following: 请参阅“echo”解释的其他答案,但如果您正在使用heredoc,例如以下内容:

echo <<<EOHTML
<td>{$entity['name']}</td>
EOHTML;

You need the curly braces to properly use the associative array. 您需要花括号来正确使用关联数组。

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

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