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";
上面的pProblem是我刚刚引入的语法错误(缺少的转义引号),与此处的文档语法相反:
$x = <<<EOF
The point of the "argument" was to illustrate the use of here documents
EOF;
这有点风格,但是我将以下内容用作定义字符串的单,双和此处文档的规则: