gpt4 book ai didi

php - 在 PHP 中使用 heredoc 有什么好处?

转载 作者:IT老高 更新时间:2023-10-28 11:41:17 26 4
gpt4 key购买 nike

使用 heredoc 有什么好处?在PHP中,你能举个例子吗?

最佳答案

heredoc 语法对我来说更简洁,它对于多行字符串和避免引用问题非常有用。过去我曾经使用它们来构建 SQL 查询:

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

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

$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";

上面的问题是我刚刚介绍的语法错误(缺少转义引号)而不是这里的文档语法:

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

有点风格,但我使用以下规则作为单、双和此处定义字符串的文档:

  • 单引号在字符串是常量时使用,例如'no variables here'
  • 双引号 当我可以将字符串放在一行上并需要变量插值或嵌入单引号时 "今天是 ${user} 的生日"
  • 此处文档用于需要格式化和变量插值的多行字符串。

关于php - 在 PHP 中使用 heredoc 有什么好处?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5673269/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com