PHP双括号字符串中的括号

Tox*_*xic 1 php string

这更像是一种更好的练习类型的问题.

我想知道在变量的双引号字符串中使用括号是否是一种好习惯.

例如:

<?php
$Variable = 'a variable';
$SingleQuotedString = 'Single quoted string with ' . $Variable;
// Single quoted string with a variable

$DoubleQuotedString = "Double quoted string with $Variable";
// Double quoted string with a variable

$DoubleQuotedStringWithBrackets = "Double quoted string with {$Variable} in brackets.";
// Double quoted string with a variable in brackets.
?>
Run Code Online (Sandbox Code Playgroud)

它不会改变简单测试的输出或代码,显然有效.我只是感到困惑,因为没有多少人这样做,我没有看到建议或人们不同意,我一直在使用它们.

感谢您的任何反馈!

Mar*_*tin 9

花括号是允许使用数组和对象,即:

$string = "my array value: {$foo['bar']}";
Run Code Online (Sandbox Code Playgroud)

要么

$string = "my object value: {$foo->bar}";
Run Code Online (Sandbox Code Playgroud)


Mar*_*der 5

最快、最干净的版本是第一个。双引号字符串中的变量...只是“感觉”不对。

$SingleQuotedString = 'Single quoted string with ' . $Variable;
Run Code Online (Sandbox Code Playgroud)

我能想到的唯一派上用场的情况是当你有一个

$string = "with a {$load} of {$variables} in {one} {sentence}!";
Run Code Online (Sandbox Code Playgroud)

否则可读性会受到很大影响。

  • 嗯...我曾经在一家公司工作过,该公司开发了一款严重依赖性能的拍卖软件。我们甚至无法使用包含。:P (2认同)