问题描述
我想知道,将 PHP 变量插入字符串的正确方法是什么?
这样:
I am wondering, What is the proper way for inserting PHP variables into a string?
This way:
echo "Welcome ".$name."!"
或者这样:
echo "Welcome $name!"
这两种方法都适用于我的 PHP v5.3.5
.后者更短更简单,但我不确定第一个是更好的格式还是被接受为更合适.
Both of these methods work in my PHP v5.3.5
. The latter is shorter and simpler but I'm not sure if the first is better formatting or accepted as more proper.
推荐答案
在这两种语法之间,你应该真正选择你喜欢的一种:-)
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.
结果是一样的;即使有性能影响,这些也无关紧要.
The result will be the same; and even if there are performance implications, those won't matter.
作为旁注,所以我的回答更完整一些:你想要做这样的事情的那一天:
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, "!";
(但是,正如我之前所说,这并不重要......)
这篇关于PHP - 在字符串中连接或直接插入变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!