dsfdsf21321 2011-08-25 08:27
浏览 44
已采纳

if / else与heredoc不符合预期

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.

  • 写回答

1条回答 默认 最新

  • dqyp50298 2011-08-25 08:33
    关注

    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 second EOD; has whitespace behind the EOD;. Select the code (or view in hexedit or showing whitespace) to see:

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

    Image clarification:

    http://img803.imageshack.us/img803/826/whitespaceheredoc.png

    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.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 (标签-matlab)
  • ¥100 求看看这个数学建模,有偿
  • ¥15 深度学习目标检测现在框架加注意力的创新可以投几区?
  • ¥15 PdfiumViewer pdf转图片
  • ¥15 利用Java连接API接口总是出问题
  • ¥15 请教一个关于镜头标定,棋盘格格子大小的问题(畸变测试)
  • ¥15 安装GroudingDINO RuntimeError: Error compiling objects for extension
  • ¥15 急!C++指针编写相关的问题
  • ¥15 kerberos身份认证配置问题
  • ¥30 用python写一个多签情况下波场的代理资源和回收资源