Heredoc Interfering with Code Indentation

HEREDOC interfering with code indentation

Thank goodness this feature has finally landed in php 7.3 via RFC: Flexible Heredoc and Nowdoc Syntaxes

So now your example can cleanly be written as:

class myclass
{
function __construct()
{
$a = some_code();
$b = some_more_code();
$x = <<<EOT

line1
line2
line3
line4

EOT;

$c = even_more_code();
$b = still_more_code();
}
}

PHP: Using Proper Indentation with Heredocs

It's a limitation of PHP to properly format Heredoc statements. It's a parser limitation. As the documentation states:

It is very important to note that the
line with the closing identifier must
contain no other characters, except
possibly a semicolon (;). That means
especially that the identifier may not
be indented, and there may not be any
spaces or tabs before or after the
semicolon. It's also important to
realize that the first character
before the closing identifier must be
a newline as defined by the local
operating system. This is \n on UNIX
systems, including Mac OS X. The
closing delimiter (possibly followed
by a semicolon) must also be followed
by a newline.

If this rule is broken
and the closing identifier is not
"clean", it will not be considered a
closing identifier, and PHP will
continue looking for one. If a proper
closing identifier is not found before
the end of the current file, a parse
error will result at the last line.

It's unknown if this is gonna be resolved in the future of PHP.

php formatting string EOD

Apart that you can't indent, you can't also write this line

"if (!confirm('".Module::t("Approve") . "?')) return false;";

inside the heredoc.

Where are the setting for heredoc format style in PhpStorm 9.0.2

On PhpStorm 9 and 10, it can be changed by Assignment statement -> Assignment sign on next line setting on Wrapping and Braces tab.

This setting will also affect following code style:

Off

class Foo
{
var $numbers = array( "one",
"two",
"three",
"four",
"five",
"six" );
}

On

class Foo
{
var $numbers
= array( "one",
"two",
"three",
"four",
"five",
"six" );
}

here-document gives 'unexpected end of file' error

The EOF token must be at the beginning of the line, you can't indent it along with the block of code it goes with.

If you write <<-EOF you may indent it, but it must be indented with Tab characters, not spaces. So it still might not end up even with the block of code.

Also make sure you have no whitespace after the EOF token on the line.

Why is there an error in this PHP code?

The first line of heredoc string must have NO indentation... like this:

    function __construct()
{
$a = some_code();
$b = some_more_code();
$x = <<<EOT

line1
line2
line3
line4

EOT;

$c = even_more_code();
$b = still_more_code();
...
...
...

see more here: HEREDOC interfering with code indentation



Related Topics



Leave a reply



Submit