为什么 PHP heredoc 无法保留换行符?

Why does PHP heredoc fail to preserve linebreaks?

docs:

Heredoc text behaves just like a double-quoted string, without the double quotes.

此代码

<?php
echo "dc:<"."


".">";
echo "hd:<".<<<EOD


EOD
.">";

应该输出:

dc:<


>hd:<


>

而是(在 PHP V5.6.13 上 Windows)它输出:

dc:<


>hd:<
>

怎么了?

我对此进行了试验,我认为我可以做出有根据的猜测。

在双引号字符串部分有 3 个换行符:一个从第 2 行到第 3 行,一个从第 3 行到第 4 行,一个从第 4 行到第 5 行。

在 heredoc 部分你只有一个换行符。我认为 heredoc 部分从第一个 EOD 标记之后的行开始,到最后一个 EOD 标记之前的行结束。因此,在您的 heredoc 中,第 7 行到第 8 行只有一个换行符,您可以在输出中看到这一点(最后 <> 之间的换行符)。 如果您向 heredoc 部分添加更多换行符,那么您将在输出中看到它们。

希望这有助于说明:

<?php
echo "dc:<"."          <-- first newline
                       <-- second newline
                       <-- third newline
".">";
echo "hd:<".<<<EOD     <-- heredoc starts after this part
                       <-- only one newline here
                       <-- heredoc ends here so this newline doesn't count
EOD
.">";


回复您的评论:

"In the heredoc section you only have one newline." I have three

是的,但正如我所说,我认为第一个和最后一个换行符被忽略了。

"I think that the heredoc section starts on the line AFTER the first EOD token and ends on the line BEFORE the last EOD token" No. See the doc quote I posted.

查看您链接到的文档中的这段文字(强调我的):

A third way to delimit strings is the heredoc syntax: <<<. After this operator, an identifier is provided, then a newline. The string itself follows, and then the same identifier again to close the quotation.

注意它说 字符串本身 跟在换行符后面。我相信这证明了我的断言,即第一个换行符被省略,因为它是 heredoc 构造的一部分。不可否认,这只解释了第一个换行符。但我相信出于同样的原因,最后一个换行符被忽略了。

"If you add more newlines to the heredoc section then you will see them in your output." Yup, but still my output has the wrong quantity of newlines.

That quote being: "Heredoc text behaves just like a double-quoted string, without the double quotes."

我认为如果您的双引号字符串部分的结构如下...

<?php
echo 'dc:<'.
"
"
.'>';
echo "hd:<".<<<EOD


EOD
.">";

然后它就会像您期望的那样工作。换句话说,heredoc 与双引号字符串 没有双引号 的工作方式相同。试试吧。