Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why do these Heredoc and Nowdoc cause errors?

I've already found some solutions, but can't know what happened...

Example 1:

<?php

echo <<< EOD
test
EOD;

Example 2:

<?php

echo <<< 'EOD'
test
EOD;

Output 1,2:

PHP Parse error:  syntax error, unexpected end of file, expecting variable (T_VARIABLE) or heredoc end (T_END_HEREDOC) or ${ (T_DOLLAR_OPEN_CURLY_BRACES) or {$ (T_CURLY_OPEN)

Example 3:

<?php

echo <<< EOD
test
EOD;

?>

Example 4:

<?php

echo <<< 'EOD'
test
EOD;

?>

Example 5:

<?php

echo <<< EOD
test
EOD;
'dummy';

Example 6:

<?php

echo <<< 'EOD'
test
EOD;
'dummy';

Output 3,4,5,6:

test
like image 859
mpyw Avatar asked May 25 '13 01:05

mpyw


People also ask

What is the purpose of using the heredoc and Nowdoc in PHP?

Heredoc and nowdoc provide useful alternatives to defining strings in PHP to the more widely used quoted string syntax. They are especially useful when we need to define a string that spans multiple lines (new lines are also interpreted when used in quoted strings) and where use of whitespace is important.

What is heredoc and why might it be useful?

A heredoc is a way to define a multiline string, while maintaining the original indentation & formatting. You can use a Heredoc to embed snippets of SQL, HTML, or even XML code. A Heredoc starts with <<- , followed by a word that represents the name for the heredoc, then the contents.

What is the use of heredoc?

Here document (Heredoc) is an input or file stream literal that is treated as a special block of code. This block of code will be passed to a command for processing. Heredoc originates in UNIX shells and can be found in popular Linux shells like sh, tcsh, ksh, bash, zsh, csh.

What is a heredoc string?

In computing, a here document (here-document, here-text, heredoc, hereis, here-string or here-script) is a file literal or input stream literal: it is a section of a source code file that is treated as if it were a separate file.


2 Answers

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.

like image 154
Marc B Avatar answered Oct 05 '22 00:10

Marc B


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.

like image 21
Stephane Winnepenninckx Avatar answered Oct 05 '22 02:10

Stephane Winnepenninckx