PHP Heredoc String Rules

陌路散爱 提交于 2019-12-04 09:19:46

this is a simple use:

$bar = "stackoverflowpro";
$foo = <<<HTML
<p>Hello $bar</p>
HTML;
echo <<< _html

... some html code here ...

_html;

Important is that the closing tag is precisely the same as defined after the "<<<" and that the closing tag is placed without indent (no tabs, completely sticky to the left) and is closed by a ";".

Note: the "_" is not required, but I use it to indicate better that is a heredoc which is closing.

The closing heredoc identifier MUST NOT have any characters at all between the start of line and the identifier, it MAY have a single ; IMMEDIATELY afterwards and MUST NOT have any other characters after it. If the identifier gets indented it must be treated as part of the heredoc string. The only character that may appear before the newline is ;. You can't even include any whitespace between the identifer and the ; or between the ; and the newline. This means that if you use a heredoc inside a function call, you must insert a line break just after the closing identifier (i.e. before any , or ), etc.).

In other words, the only thing that can appear on the line with the closing identifier is the identifier itself and optionally one semicolon (;) immediately after the identifier. The next chararcter (if not at End-Of-File) MUST be a valid newline character for the operating system that PHP is running on.

This is a valid heredoc string:

$text = <<<EOT
Hello!
EOT;

This heredoc string hasn't been closed and   EOT; is considered part of the string:

  $text = <<<EOT
  Hello!
  EOT;

The previous example fixed:

  $text = <<<EOT
  Hello!
EOT;

A heredoc inside a function call (note that ); must appear on a new line to work):

print(<<<EOT
Hello!
EOT
);

The same as above with very weird indentation (note that the only thing on the closing identifier line is the identifier and a newline). Hello! will have five spaces before it in the string:

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