Flexible Heredoc and Nowdoc in PHP 7.3

Erstellt: | Aktualisiert:

Heredoc and Nowdoc offer the simple integration of long strings into PHP.

Heredoc works like the double quotes in PHP, therefore you can add variables into your heredoc string as well.

Nowdoc works like a single quote in PHP and there is no interpretation of the string in any way.

Implementation up to PHP 7.2


function whatever72() {
    $number = rand(1,10);
    return <<<HTML
        <p>Whatever number {$number} over here.</p>
HTML;
}

The requirements for this code to work are strict restrictments for the heredoc syntax:

  • The start tag HTML needs to be exactly the same as the end tag HTML
  • The end tag MUST be at the beginning of the line
  • The end tag MUST be without any additional characters, except semicolon
  • The end tag MUST be without any additional code afterwards

The nowdoc syntax is pretty much the same, just the start tag is enclosed by single quotes:

    return <<<'HTML'

These requirements look pretty weird in your code and lead to errors as well. Additionally it is not possible to remove any of the indentation of your string.

Implementation starting with PHP 7.3

Regarding the heredoc syntax, there is a major improvement in 7.3, allowing to add proper indentation to your code.


function whatever73() {
    $number = rand(1,10);
    return <<<HTML
        <p>Whatever number {$number} over here.</p>
        HTML; // code afterwards possible as well - and comments
}

Now the end tag can be indented as well and the number of spaces the end tag is indented will be removed from the whole string. See this two examples:


return <<<HTML
    <p>Whatever number {$number} over here.</p>
    HTML;

// Results in:
// <p>Whatever number 5 over here.</p>

return <<<HTML
    <p>Whatever number {$number} over here.</p>
HTML;

// Results in:
//    <p>Whatever number 5 over here.</p>