SyntaxStudy
Sign Up
PHP Heredoc & Nowdoc Syntax
PHP Intermediate 7 min read

Heredoc & Nowdoc Syntax

When you need multi-line strings, heredoc and nowdoc provide a clean alternative to concatenation or escaped quotes.

  • Heredoc (<<<EOT) behaves like a double-quoted string — variables are interpolated.
  • Nowdoc (<<<'EOT') behaves like a single-quoted string — no interpolation, content is literal.

Since PHP 7.3 the closing marker no longer needs to be at column 0, so heredoc/nowdoc can be indented naturally inside functions and classes.

Example
<?php
$product = 'Widget';
$price   = 9.99;

// Heredoc — variables ARE interpolated
$html = <<<EOT
    <div class="product">
        <h2>$product</h2>
        <p>Price: \$$price</p>
    </div>
    EOT;

echo $html;

// Nowdoc — NO interpolation (ideal for code snippets or SQL)
$sql = <<<'SQL'
    SELECT *
    FROM products
    WHERE price < $price
    SQL;

echo $sql;
// Output contains literal "$price", not 9.99

// Useful for embedding HTML in mailers, templates, etc.
function emailBody(string $name): string
{
    return <<<EOT
        Hello, $name!
        Welcome to our platform.
        EOT;
}
Pro Tip

Tip: Prefer nowdoc for SQL, regular expressions, or any content that must not undergo variable interpolation — it eliminates a whole class of accidental substitution bugs.