Zend PHP 7 Certification – Strings – HEREDOC & NOWDOC

This post covers the HEREDOC & NOWDOC section of the Strings chapter when studying for the Zend PHP 7 Certification.

HEREDOC

The heredoc syntax uses the operator: <<<. After this operator, an identifier is provided, then a newline. The string itself follows, and then the same identifier again to close the quotation.

<?php

$string = <<<STR
This is some text you see.
STR; // Outputs: This is some text you see.

Heredoc text behaves just like a double-quoted string, without the double quotes. This means that quotes in a heredoc do not need to be escaped, but the escape codes listed above can still be used. Variables are also expanded.

<?php

$name = "John";

echo $string = <<<STR
This person is called $name
STR; // Outputs: This person is called John
<?php

$name = "John";

echo $string = <<<STR
This person is called $name \n He is 40 years old.
STR; // Outputs: This person is called John
                 He is 40 years old.

Heredocs cannot be used for initialising class properties. Since PHP 5.3, this limitation is valid only for heredocs containing variables.

<?php

// Invalid
class foo {
    public $bar = <<<EOT
bar
    EOT;
}

NOWDOC

Nowdocs are to single-quoted strings what heredocs are to double-quoted strings. A nowdoc is specified similarly to a heredoc, but no parsing is done inside a nowdoc. This syntax was introduced in PHP 5.3.

A nowdoc is identified with the same <<< sequence used for heredocs, but the identifier which follows is enclosed in single quotes, for example: <<<'EOT'.

<?php

$name = "John";

echo $string = <<<'STR'
This person is called $name
STR; // Outputs: This person is called $name

When using either the HEREDOC or NOWDOC syntax, you may notice that the code within the declaration is not indented properly, and that attempting to indent causes the syntax to break.

Whilst there are workarounds to indent the code, such as including the syntax in a different file, these methods can cause readability issues. As long as the code within the declarations isn’t too complex, not indenting the code won’t cause problems.

View the other sections:

Note: This article is based on PHP version 7.1.