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#的问题,如何解决?(相关搜索:信噪比,系统容量)
  • ¥500 52810做蓝牙接受端
  • ¥15 基于PLC的三轴机械手程序
  • ¥15 多址通信方式的抗噪声性能和系统容量对比
  • ¥15 winform的chart曲线生成时有凸起
  • ¥15 msix packaging tool打包问题
  • ¥15 finalshell节点的搭建代码和那个端口代码教程
  • ¥15 Centos / PETSc / PETGEM
  • ¥15 centos7.9 IPv6端口telnet和端口监控问题
  • ¥20 完全没有学习过GAN,看了CSDN的一篇文章,里面有代码但是完全不知道如何操作