在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有什么优势?
发布评论