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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5605965/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 21:58:00  来源:igfitidea点击:

PHP - concatenate or directly insert variables in string

phpstringvariablesconcatenation

提问by Web_Designer

I am wondering, What is the proper way for inserting PHP variables into a string?

This way:

我想知道,将 PHP 变量插入字符串的正确方法是什么?

这边走:

echo "Welcome ".$name."!"

Or this way:

或者这样:

echo "Welcome $name!"

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.

这两种方法都适用于我的PHP v5.3.5. 后者更短更简单,但我不确定第一个是更好的格式还是被接受为更合适。

回答by Pascal MARTIN

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 matter1.

结果是一样的;即使有性能影响,这些也无关紧要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 will interpret your code as if you were trying to use the $namesvariable -- which doesn't exist. - note that it will only work if you use "" not '' for your string.

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

That day, you'll need to use {}:

那天,你需要使用{}

echo "Welcome {$name}s!"

No need to fallback to concatenations.

无需回退到串联。


Also note that your first syntax:


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

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

Could probably be optimized, avoiding concatenations, using:

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

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

(But, as I said earlier, this doesn't matter much...)

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


1 - Unless you are doing hundreds of thousands of concatenations vs interpolations -- and it's probably not quite the case.


1 - 除非您正在执行数十万次串联与插值 - 情况可能并非如此。

回答by Michael

Double-quoted strings are more elegant because you don't have to break up your string every time you need to insert a variable (like you must do with single-quoted strings).

双引号字符串更优雅,因为每次需要插入变量时都不必拆分字符串(就像必须使用单引号字符串一样)。

However, if you need to insert the return value of a function, this cannot be inserted into a double-quoted string--even if you surround it with braces!

但是,如果您需要插入函数的返回值,则不能将其插入双引号字符串中——即使您用大括号将其括起来!

//syntax error!!
//$s = "Hello {trim($world)}!"

//the only option
$s = "Hello " . trim($world) . "!";

回答by Olivier Royo

Since php4 you can use a string formater:

从 php4 开始,您可以使用字符串格式化程序:

$num = 5;
$word = 'banana';
$format = 'can you say %d times the word %s';
echo sprintf($format, $num, $word);

Source: sprintf()

来源:sprintf()

回答by Manos Dilaverakis

Either one is fine. Use the one that has better visibility for you. And speaking of visibility you can also check out printf.

任何一个都可以。使用对您来说具有更好可见性的那个。说到可见性,您还可以查看printf

回答by Frosty Z

From the point of view of making thinks simple, readable, consistentand easy to understand(since performance doesn't matter here):

从 make thinks simplereadable一致易于理解的角度来看(因为这里的性能并不重要):

  • Using embedded vars in double quotes can lead to complex and confusing situations when you want to embed object properties, multidimentional arrays etc. That is, generally when reading embedded vars, you cannot be instantly 100% sure of the final behavior of what you are reading.

  • You frequently need add crutches such as {}and \, which IMO adds confusion and makes concatenation readability nearly equivalent, if not better.

  • As soon as you need to wrap a function call around the var, for example htmlspecialchars($var), you have to switch to concatenation.

  • AFAIK, you cannot embed constants.

  • 当您想要嵌入对象属性、多维数组等时,在双引号中使用嵌入的 vars 会导致复杂和混乱的情况。也就是说,通常在读取嵌入的 vars 时,您无法立即 100% 确定您正在阅读的内容的最终行为.

  • 您经常需要添加诸如{}and 之类的拐杖\,这会增加 IMO 的混乱并使串联可读性几乎等效,甚至更好。

  • 例如htmlspecialchars($var),一旦您需要在 var 周围包装函数调用,就必须切换到串联。

  • AFAIK,您不能嵌入常量。

In some specific cases, "double quotes with vars embedding" can be useful, but generally speaking, I would go for concatenation(using single or double quotes when convenient)

在某些特定情况下,“带有 vars 嵌入的双引号”可能很有用,但一般来说,我会去连接(方便时使用单引号或双引号)

回答by Denis V

I know this question already has a chosen answer, but I found this articlethat evidently shows that string interpolation works faster than concatenation. It might be helpful for those who are still in doubt.

我知道这个问题已经有一个选择的答案,但我发现这篇文章显然表明字符串插值比串联工作得更快。对于那些仍然有疑问的人来说,这可能会有所帮助。

回答by Khez

Go with the first and use single quotes!

使用第一个并使用单引号!

  1. It's easier to read, meaning other programmers will know what's happening
  2. It works slightly faster, the way opcodes are created when PHP dissects your source code, it's basically gonna do that anyway, so give it a helping hand!
  3. If you also use single quotes instead of double quotes you'll boost your performance even more.
  1. 它更容易阅读,这意味着其他程序员会知道发生了什么
  2. 它的运行速度稍快一些,就像 PHP 剖析您的源代码时创建操作码的方式一样,无论如何它基本上都会这样做,所以请帮帮它!
  3. 如果您还使用单引号而不是双引号,您将进一步提高性能。

The only situations when you should use double quotes, is when you need \r, \n, \t! The overhead is just not worth it to use it in any other case.

应该使用双引号的唯一情况是当您需要\r, \n, \t! 在任何其他情况下使用它的开销是不值得的。

You should also check PHP variable concatenation, phpbench.comfor some benchmarks on different methods of doing things.

您还应该检查PHP variable concatenation, phpbench.com以获取有关不同处事方法的一些基准。

回答by Your Common Sense

It only matter of taste.
Use whatever you wish.

这只是口味问题。
随意使用。

Most of time I am using second one but it depends.

大多数时候我使用第二个,但这取决于。

Let me suggest you also to get yourself a good editor which will highlight a variable inside of a string

让我建议你也给自己一个好的编辑器,它会突出显示字符串中的变量

回答by David Gillen

Do not concatenate. It's not needed, us commas as echo can take multiple parameters

不要串联。不需要,我们用逗号作为 echo 可以接受多个参数

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

Regarding using single or double quotes the difference is negligible, you can do tests with large numbers of strings to test for yourself.

关于使用单引号或双引号,差异可以忽略不计,您可以使用大量字符串进行测试以进行测试。

回答by Shakti Singh

You Should choose the first one. They have no difference except the performance the first one will be the fast in the comparison of second one.

你应该选择第一个。除了第一个的性能在第二个的比较中更快之外,它们没有区别。

If the variable inside the double quote PHP take time to parse variable.

如果变量里面双引号 PHP 需要时间来解析变量。

Check out this Single quotes or double quotes for variable concatenation?

看看这个单引号或双引号变量连接?

This is another example Is there a performance benefit single quote vs double quote in php?

这是另一个例子在 php 中单引号和双引号有性能优势吗?

I did not understand why this answer in above link get upvoted and why this answer got downvote.

我不明白为什么上面链接中的这个答案得到了赞成,为什么这个答案得到了反对。

As I said same thing.

正如我所说的一样。

You can look at here as well

你也可以看看这里

What is faster in PHP, single or double quotes?

PHP 中哪个更快,单引号还是双引号?