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.

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

报告相同问题?