且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

PHP - 在字符串中连接或直接插入变量

更新时间:2023-02-06 13:40:35

在这两种语法之间,你应该真正选择你喜欢的一种:-)

Between those two syntaxes, you should really choose the one you prefer :-)

就我个人而言,在这种情况下,我会采用您的第二个解决方案(变量插值),我发现它更易于编写和阅读.

Personally, I would go with your second solution in such a case (Variable interpolation), which I find easier to both write and read.

结果是一样的;即使有性能影响,这些也无关紧要 1.

The result will be the same; and even if there are performance implications, those won't matter 1.


作为旁注,所以我的回答更完整一些:你想要做这样的事情的那一天:


As a sidenote, so my answer is a bit more complete: the day you'll want to do something like this:

echo "Welcome $names!";

PHP 将解释您的代码,就好像您试图使用 $names 变量一样 -- 该变量不存在.- 请注意,它仅在您对字符串使用 "" 而不是 '' 时才有效.

PHP will interpret your code as if you were trying to use the $names variable -- which doesn't exist. - note that it will only work if you use "" not '' for your string.

那天,您需要使用 {}:

echo "Welcome {$name}s!"

无需回退到串联.


还要注意你的第一个语法:


Also note that your first syntax:

echo "Welcome ".$name."!";

可能会优化,避免串联,使用:

Could probably be optimized, avoiding concatenations, using:

echo "Welcome ", $name, "!";

(但是,正如我之前所说,这并不重要......)


1 - 除非您要进行数十万次串联与插值 - 否则可能并非如此.