我应该在字符串中使用大括号还是连接变量? [英] Should I use curly brackets or concatenate variables within strings?

查看:114
本文介绍了我应该在字符串中使用大括号还是连接变量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在字符串中连接变量或使用花括号代替是有利有弊?

Is there an advantage or disadvantage to concatenating variables within strings or using curly braces instead?

级联:

$greeting = "Welcome, " . $name . "!";

大括号:

$greeting = "Welcome, {$name}!";

我个人总是连接字符串,因为我使用 UEStudio ,并在连接时以不同的颜色突出显示PHP变量.但是,如果不分解变量,则不会.只是让我的眼睛更容易找到长字符串等中的PHP变量.

Personally, I've always concatenated my strings, because I use UEStudio, and it highlights PHP variables with a different color when concatenated. However, when the variable is not broken out, it does not. It just makes it easier for my eyes to find PHP variables in long strings, etc.

人们对于SQL感到困惑.这是 不是 此问题的内容.我已经更新了示例以避免混淆.

People are confusing this about being about SQL. This is not what this question is about. I've updated my examples to avoid confusion.

推荐答案

如果查看输出,以下所有内容都相同.

All of the following does the same if you look at the output.

  1. $greeting = "Welcome, " . $name . "!";
  2. $greeting = 'Welcome, ' . $name . '!';
  3. $greeting = "Welcome, $name!";
  4. $greeting = "Welcome, {$name}!";
  1. $greeting = "Welcome, " . $name . "!";
  2. $greeting = 'Welcome, ' . $name . '!';
  3. $greeting = "Welcome, $name!";
  4. $greeting = "Welcome, {$name}!";

您不应使用选项1,而应使用选项2.选项3和4相同.对于简单变量,花括号是可选的.但是,如果使用数组元素,则必须使用花括号;例如:$greeting = "Welcome, {$user['name']}!";.因此,作为标准,如果使用变量插值而不是串联,则使用花括号.

You should not be using option 1, use option 2 instead. Both option 3 and 4 are the same. For a simple variable, braces are optional. But if you are using array elements, you must use braces; e.g.: $greeting = "Welcome, {$user['name']}!";. Therefore as a standard, braces are used if variable interpolation is used, instead of concatenation.

但是,如果使用制表符(\t),换行符(\n)之类的字符,则它们必须用双引号引起来.

But if characters such as tab (\t), new-line (\n) are used, they must be within double quotations.

通常,变量插值速度很慢,但是如果要连接的变量太多,则串联的速度也可能较慢.因此,请根据其他字符中有多少个变量来决定.

Generally variable interpolation is slow, but concatenation may also be slower if you have too many variables to concatenate. Therefore decide depending on how many variables among other characters.

这篇关于我应该在字符串中使用大括号还是连接变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆