开发者

if/else with heredoc not behaving as expected

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 fals开发者_如何学JAVAe I just get Hi UsernameGood Bye which is even more puzzling.


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:

if/else with heredoc not behaving as expected

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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜