if/else 与 Heredoc 的行为不符合预期
我正在使用 Heredoc 构建一个简单的文本电子邮件,但由于某种原因,我在 if/else 条件周围得到了奇怪的结果:
<?php
$message = <<<EOD
Hi Username
EOD;
echo $message.'<hr>';
if(true) {
$message .= <<<EOD
Thanks for logging in
EOD;
} else {
$message .= <<<EOD
Thanks for signing up.
EOD;
}
echo $message.'<hr>';
$message .= <<<EOD
Good Bye
EOD;
echo '<pre>'.$message.'</pre>';
输出:
Hi UsernameThanks for logging in
EOD;
} else {
Hi Username .= <<<EOD
Thanks for signing up. Good Bye
出于某种原因,它正在输出我的 PHP - 如果我将 true 更改为 false,我只会得到 Hi UsernameGood Bye
这更令人费解。
I am using heredoc to build a simple text email, but for some reason I am getting strange results around my if/else conditional:
<?php
$message = <<<EOD
Hi Username
EOD;
echo $message.'<hr>';
if(true) {
$message .= <<<EOD
Thanks for logging in
EOD;
} else {
$message .= <<<EOD
Thanks for signing up.
EOD;
}
echo $message.'<hr>';
$message .= <<<EOD
Good Bye
EOD;
echo '<pre>'.$message.'</pre>';
Output:
Hi UsernameThanks for logging in
EOD;
} else {
Hi Username .= <<<EOD
Thanks for signing up. Good Bye
For some reason it's outputting my PHP - if I change true to false I just get Hi UsernameGood Bye
which is even more puzzling.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您的
EOD;
应该是该行中出现的所有内容。只有那4个字符。您对第一个、第三个和第四个
EOD;
做得很好,但第二个EOD;
在 EOD; 后面有空格。选择代码(或在十六进制编辑器中查看或显示空格)以查看:图像澄清:
这会导致第二个 EOD 和第三个 EOD 之间的所有内容都被视为此处文档:)
如果您使用 EOD1, EOD2、EOD3 和 EOD4,您会收到警告“未找到 EOD2”或类似内容。
您不是第一个遇到此错误的人, PHP HereDoc Manualpage 甚至显示警告(在heredoc结束标记之前有空格)。 hakre 添加的内容确实是正确的,正如联机帮助页上所解释的:“可能”是分号。
Your
EOD;
should be ALL that is present on the line. Only those 4 characters.You did fine for the first, third and fourth
EOD;
, but the secondEOD;
has whitespace behind the EOD;. Select the code (or view in hexedit or showing whitespace) to see:Image clarification:
This causes everything between the second EOD and the third EOD to be considered as the here-document :)
If you would have used EOD1, EOD2, EOD3 and EOD4, you'd have gotten the warning 'EOD2 not found' or something along those lines.
You're not the first to encounter this error, the PHP HereDoc Manualpage even shows a warning (with whitespace before the heredoc endmarker). What hakre added is indeed correct, as also explained on the manpage: 'possibly' a semicolon.