New in PHP 7.3 – Flexible heredoc syntax

23 May 2020


Heredoc is a useful tool for larger strings, though they have an indentation quirk which always put me off.

To quote from the PHP Requests-for-Comments:

The heredoc and nowdoc syntaxes have very rigid requirements. This has caused them to be, in-part, eschewed by developers because their usage in code can look ugly and harm readability.

PHP 7.3 introduces two changes to the syntax for heredoc and nowdoc syntaxes:

1) Indentation for the closing marker

You are now allowed to indent the closing marker, and you can indent the heredoc text to match the closing marker.

This is especially useful when you’re using Heredoc in an already nested context.

function getAll() {
    $sql = <<<SQL
SELECT * 
FROM `table`
WHERE `bool` = 1;
SQL;
    $rows = $this->db->fetchAll($sql);
}

You can now do this. The whitespace in front of the closing marker will be ignored on all lines.

function getAll() {
    $sql = <<<SQL
        SELECT * 
        FROM `table`
        WHERE `bool` = 1;
        SQL;
    $rows = $this->db->fetchAll($sql);
    ...
}

2) Closing Marker New Line

Previously you had to have a newline after the closing marker. This is no longer required.

function getAll() {
    $sql = <<<SQL
        SELECT * 
        FROM `table`
        WHERE `bool` = 1;
        SQL;   $rows = $this->db->fetchAll($sql);
    ....
}

Not so taken with this one. But it’s a thing.

Recently I’ve been trying to add MySQL views into Laravel code for database migration and that’s a great big ugly chunk of SQL queries in the middle of a class. Heredoc is a nice way to manage it.