在PHP中使用Heredoc有什么优势?

编程入门 行业动态 更新时间:2024-10-26 00:27:37
本文介绍了在PHP中使用Heredoc有什么优势?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

在PHP中使用 heredoc 有什么好处,您可以举个例子吗?

What is the advantage of using heredoc in PHP, and can you show an example?

推荐答案

heredoc语法对我来说更干净,它对于多行字符串和避免引用问题确实很有用.回到过去,我曾经用它们来构造SQL查询:

The heredoc syntax is much cleaner to me and it is really useful for multi-line strings and avoiding quoting issues. Back in the day I used to use them to construct SQL queries:

$sql = <<<SQL select * from $tablename where id in [$order_ids_list] and product_name = "widgets" SQL;

对我来说,与使用引号相比,引入语法错误的可能性更低:

To me this has a lower probability of introducing a syntax error than using quotes:

$sql = " select * from $tablename where id in [$order_ids_list] and product_name = \"widgets\" ";

另一点是避免在字符串中转义双引号:

Another point is to avoid escaping double quotes in your string:

$x = "The point of the \"argument" was to illustrate the use of here documents";

上面的pProblem是我刚才介绍的语法错误(缺少的转义引号),与此处的文档语法相反:

The pProblem with the above is the syntax error (the missing escaped quote) I just introduced as opposed to here document syntax:

$x = <<<EOF The point of the "argument" was to illustrate the use of here documents EOF;

有点样式,但是我将以下内容用作定义字符串的单,双和此处文档的规则:

It is a bit of style, but I use the following as rules for single, double and here documents for defining strings:

    当字符串是像'no variables here' 这样的常量时,使用
  • 单引号. 当我可以将字符串放在单行上并且需要变量插值或嵌入式单引号"Today is ${user}'s birthday"
  • 时,会使用
  • 双引号
  • 此处文档,用于需要格式化和变量插值的多行字符串.
  • Single quotes are used when the string is a constant like 'no variables here'
  • Double quotes when I can put the string on a single line and require variable interpolation or an embedded single quote "Today is ${user}'s birthday"
  • Here documents for multi-line strings that require formatting and variable interpolation.

更多推荐

在PHP中使用Heredoc有什么优势?

本文发布于:2023-10-17 10:21:44,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1500632.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:有什么   优势   PHP   Heredoc

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!