问题描述
这可能是一个愚蠢的问题,但它令我震惊,在这里我问。
This might be a silly question but it struck me, and here i ask.
<?php
$x="Hi";
$y=" There";
$z = $x.$y;
$a = "$x$y";
echo "$z"."<br />"."$a";
?>
$ z
使用提供的传统串联运算符通过php和连接起来,相反$ a不会,
$z
uses the traditional concatenation operator provided by php and concatenates, conversely $a doesn't,
我的问题:
-
通过不使用串联运算符会影响性能吗?
by not using the concatenation operator, does it effect the performance?
如果不是这样,为什么根本没有串联运算符。
If it doesn't why at all have the concatenation operator.
为什么一种工作方式有两种实现方式?
Why have 2 modes of implementation when one does the work?
推荐答案
-
仅需一点点,因为PHP必须解析整个字符串以查找变量,而使用串联时,它只是将两个变量在一起。因此,它对性能的影响很小,但是对于大多数事情而言却并不明显。
Only slightly, since PHP has to parse the entire string looking for variables, while with concatenation, it just slaps the two variables together. So there's a tiny performance hit, but it's not noticeable for most things.
连接诸如 $ _ SERVER之类的变量要容易得多。 ''DOCUMENT_ROOT']
使用串联运算符(带引号,您必须将变量括在方括号中或删除数组索引中的单引号;加上它只会使字符串看起来很难看)。此外,串联运算符还为格式化提供了更大的灵活性。例如,您可以将长字符串文字分解为多行,然后将其不同部分连接起来:
It's a lot easier to concatenate variables like $_SERVER['DOCUMENT_ROOT']
using the concatenation operator (with quotes, you have to surround the variable in brackets or remove the single quotes in the array index; plus it just makes the string look all ugly). Plus, the concatenation operator allows more flexibility for formatting. For example, you can break up a long string literal onto multiple lines and then concatenate the different parts of it:
$blah = "This is a really really long string. I don't even know how " .
"long it is, but it's really long. Like, longer than an eel " .
"or even a boa constrictor. Wow.";
您还可以使用串联运算符直接在字符串文字中包含函数的返回值(您可以
You can also use the concatenation operator to directly include return values from functions in a string literal (you can't include a function call in a double-quoted string), like this:
$blah = "This has a " . fn_call() . " result, which can't go in the quotes.";
我不确定我是否完全理解您在这里的要求,但是我可以说PHP是从Perl借来的很多东西,而Perl的口头禅是有多种方法可以做到这一点。
I'm not sure I entirely understand what you're asking here, but I can say that PHP borrows a lot of things from Perl, and one of Perl's mantras is "There's more than one way to do it."
这篇关于串联运算符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!