PHP EOF(heredoc)

`heredoc` 与 `nowdoc` 的语法、缩进规则、以及常见用途。

Beginner
Key Points`<<<EOT` 是多行字符串,解析变量;`<<<'EOT'` 是 nowdoc,不解析。

heredoc

PHP
<?php
$name = "张三";
$age = 28;

$text = <<<EOT
你好,{$name}。
你今年 {$age} 岁。
这里的换行、引号 "都不需要转义"。
EOT;

echo $text, "\n";
Output
你好,张三。
你今年 28 岁。
这里的换行、引号 "都不需要转义"。

Content starts on the line after <<<EOT and ends at a line with just EOT;. Newlines and quotes are literal while variables still interpolate — ideal for HTML fragments and SQL.

nowdoc

PHP
<?php
$name = "张三";

$raw = <<<'EOT'
变量 $name 不会解析,\n 也不转义。
适合放代码示例或纯文本。
EOT;

echo $raw, "\n";
Output
变量 $name 不会解析,\n 也不转义。
适合放代码示例或纯文本。
FormInterpolatesEscapes
<<<EOT是是
<<<'EOT'否否

缩进规则(PHP 7.3+)

PHP
<?php
function render(): string
{
    $items = ['苹果', '香蕉'];

    $html = <<<HTML
        <ul>
            <li>{$items[0]}</li>
            <li>{$items[1]}</li>
        </ul>
        HTML;

    return $html;
}

echo render(), "\n";
Output
<ul>
    <li>苹果</li>
    <li>香蕉</li>
</ul>

Since PHP 7.3 the closing marker's indentation is stripped from every line. Above, HTML; is indented 8 spaces so each line loses 8 — letting heredoc sit naturally inside indented code.

The closing marker must contain only whitespace before it and nothing but ; after. Mixing tabs and spaces triggers Invalid body indentation level.

典型用途

PHP
<?php
// 1. 拼 SQL
$table = "users";
$sql = <<<SQL
SELECT id, name, email
FROM {$table}
WHERE status = 'active'
ORDER BY id DESC
LIMIT 10
SQL;
echo $sql, "\n\n";

// 2. 生成邮件正文
$body = <<<MAIL
尊敬的客户:

您的订单已发货。
感谢您的支持!
MAIL;
echo $body, "\n";
Output
SELECT id, name, email
FROM users
WHERE status = 'active'
ORDER BY id DESC
LIMIT 10

尊敬的客户:

您的订单已发货。
感谢您的支持!

Heredoc beats concatenation for SQL: no missing spaces, no quote escaping. But interpolating variables is still injectable — use prepared statements for real queries (see the PDO chapter).

Friends & Partners