Note: a minor incompatible change was made to heredoc in PHP 7.3. See the second section for the changes since PHP 7.3.
Pre PHP 7.3
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 identifier 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 character (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
);
Extra rules post PHP 7.3
In PHP 7.3 and later, the identifier is allowed to have whitespace before it, as long as it matches the whitespace indentation in the rest of the string. Spaces and tabs can't be mixed and the indentation of every line in the string must be identical. Extra horizontal whitespace of any type can appear immediately after the indentation whitespace except immediately before the closing identifier.
This previous example is now valid in PHP 7.3 and above:
$text = <<<EOT
Hello!
EOT;
The identifier can no longer appear anywhere else within the string, except within a longer identifier or after printing (non-whitespace) characters. Identifiers consist of letters and underscores, but not numbers or symbols.
Invalid (+
is not a letter or underscore):
$text = <<<FOO
Hello!
FOO+
FOO;
Valid (Hello!\n FOOD
):
$text = <<<FOO
Hello!
FOOD
FOO;
Valid (Hello!\n A FOO
):
$text = <<<FOO
Hello!
A FOO
FOO;
The closing identifier no longer needs to be the only thing on its line (except for the previously mentioned optional semicolon and indentation).
Valid (Hello!1588648007
):
$text = <<<FOO
Hello!
FOO . time();