Why do these Heredoc and Nowdoc cause errors?

坚强是说给别人听的谎言 提交于 2019-11-30 10:21:40

You probably have spaces after the terminator in your first two examples, e.g.

EOD;[space]

With this:

<?php
echo <<<EOL
test
EOL;[space]

I get your error message, but WITHOUT the space, there's no error. And that's true whether there's a closing ?> or not.

Stephane Winnepenninckx

The closing delimiter must start on the first column, no spaces nor tabs allowed in front of it. Be aware that things are changing in 5.5 and 5.6

'EOD' is equivalent to echo ' ',
"EOD" is equivalent to echo " " about variable substitutions.

The closing delimiter doesn't take any single of double quotes.

Heredoc is very finicky. Make sure there are no spaces after your initial EOD. And the final EOD; must be on it's own line, with no spaces before it, and nothing else on that line. It's those spaces that give most people trouble.

And the quotes around 'EOD' aren't necessary.

It took me sometime to master heredoc and nowdoc. Heredoc is a very tricky business. Here is the trick, the terminators should always be on singles lines except for the beginning terminator where you can add a variable or echo the string out and dont forget its is also not allowed to indent the closing tag

<?php

$string = <<<EXP // There should be nothing following this terminator <<<EXP
    You string goes here and it can include commas, quotes etc
EXP;// This should be on a single line without anything else. Hit enter to make it     contain      this line, even if there is nothing to write, still hit enter, because it     should be the master of this line

$string = <<<EXP2
I am a developer.
EXP2// Hit enter, please always do

echo $string // Works perfect

?>

One more thing: the closing tag is not "whatever you give", it must be a valid identifier with alphanumerics only (underscores are fine), if you give it any other character you'll be sorely disappointed.

Look:

$str = <<<'HEY WHAT THE HECK'

    This will not work
    and doesn't help you understand why

HEY WHAT THE HECK
;

PHP will give you a syntax error. Now if you remove the spaces,

$str = <<<'HEYWHATTHEHECK'

    Suddenly it's all peaches & cream

HEYWHATTHEHECK
;

(I just tried to use some UUID to make sure it won't happen inside the string. After 25 minutes of swearing I finally realized this.)

Happy nowdocking!

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!