Wes*_*Wes 212
这里的doc语法对我来说更清晰,它对多行字符串和避免引用问题非常有用.在那天我曾经使用它们构建SQL查询:
$sql = <<<SQL
select *
from $tablename
where id in [$order_ids_list]
and product_name = "widgets"
SQL;
Run Code Online (Sandbox Code Playgroud)
对我来说,引入语法错误的概率低于使用引号:
$sql = "
select *
from $tablename
where id in [$order_ids_list]
and product_name = \"widgets\"
";
Run Code Online (Sandbox Code Playgroud)
另一点是避免在字符串中转义双引号:
$x = "The point of the \"argument" was to illustrate the use of here documents";
Run Code Online (Sandbox Code Playgroud)
上面的问题是我刚刚介绍的语法错误(缺少的转义引用),而不是这里的文档语法:
$x = <<<EOF
The point of the "argument" was to illustrate the use of here documents
EOF;
Run Code Online (Sandbox Code Playgroud)
这是一种风格,但我使用以下作为单,双和此文档的规则来定义字符串:
'no variables here'"Today is ${user}'s birthday"Jak*_*son 67
由于可读性和可维护性的提高,Heredoc是引用字符串的绝佳替代品.您不必转义引号,(好)IDE或文本编辑器将使用正确的语法突出显示.
一个非常常见的例子:在PHP中回显HTML:
$html = <<<HTML
<div class='something'>
<ul class='mylist'>
<li>$something</li>
<li>$whatever</li>
<li>$testing123</li>
</ul>
</div>
HTML;
// sometime later
echo $html;
Run Code Online (Sandbox Code Playgroud)
易于阅读.易于维护.
另一种方法是回显引用的字符串,最终包含转义引号,IDE不会突出显示该语言的语法,这会导致可读性差,维护更加困难.
更新了您的常识的答案
当然,您不希望将SQL查询突出显示为HTML.要使用其他语言,只需更改语法中的语言:
$sql = <<<SQL
SELECT * FROM table
SQL;
Run Code Online (Sandbox Code Playgroud)
一些IDE会自动高亮显示heredoc字符串中的代码 - 这使得使用heredoc对xml或html进行视觉上的吸引力.
我个人喜欢它的更长部分即XML,因为我不必关心引用引号字符,只需粘贴XML即可.
首先,所有原因都是主观的.
这更像是品味而不是理由.
就个人而言,我发现heredoc相当无用,偶尔使用,大部分时间我需要将一些HTML放入变量并且不想打扰输出缓冲,例如形成HTML电子邮件消息.
格式化不适合一般缩进规则,但我不认为这是一个大问题.
//some code at it's proper level
$this->body = <<<HERE
heredoc text sticks to the left border
but it seems OK to me.
HERE;
$this->title = "Feedback";
//and so on
Run Code Online (Sandbox Code Playgroud)
至于接受的答案中的例子,它只是作弊.
如果一个人不会欺骗他们,那么字符串示例实际上更简洁
$sql = "SELECT * FROM $tablename
WHERE id in [$order_ids_list]
AND product_name = 'widgets'";
$x = 'The point of the "argument" was to illustrate the use of here documents';
Run Code Online (Sandbox Code Playgroud)