Tuesday, 18 September 2018

PHP's nowdoc strings

PHP has heredoc syntax like other programming languages to interpolate variables into large string blocks (which I've covered in an earlier post). In PHP 5.3.0 a new string delimiter was introduced called "nowdoc" which works in the same was as heredoc but acts like a single quoted string, so no variable interpolation or parsing is done.

Nowdoc example

A nowdoc string looks very similar to a heredoc string; the only difference is the block identifier (END_OF_STRING in the example below) is enclosed by single quotes:
$string = <<<'END_OF_STRING'
    ... some content here ...
END_OF_STRING;

The rules

The rules are the same as for heredoc, but nothing within the string needs to be escaped because there is no variable interpolation or parsing done.
A now block starts with <<< and then a block identifier enclosed by single quotes. It then ends with the name of the block identifier followed by a semi-colon. In the above example the identifier is "END_OF_STRING". Note that the closing identifier is not enclosed with single quotes.
The closing identifier must start on a new line, and there must not be any white space between the start of the line and the start of the label name, otherwise the nowdoc block does not end.
The identifier can contain any alpha-numeric character and underscores, and must start with a non-numeric character or an underscore.
Identifier names are case-sensitive.

Example with variable like contents

The following example shows how what would normally be a variable in a double quoted string or a heredoc block is not interpolated with nowdoc:
echo <<<'END_OF_HTML'
    $hello this is {$a->test}
END_OF_HTML;
This would echo:
$hello this is {$a->test}
whereas with a heredoc $hello would be replaced with the value assigned to the $hello variable and {$a->test} with the value assigned to the test property of the $a object.

Nowdoc is only available from PHP 5.3.0

Note again that the nowdoc syntax is only available from PHP 5.3.0 and will not work in older versions. If you attempt to use it in a version < 5.3.0 you will get an error message like this:
Parse error: syntax error, unexpected T_SL in ... on line ...

Related posts:

0 comments:

Post a Comment