PHP的heredoc和nowdoc使用方式

2023-03-31 11:00:56    技术分享   

  

Heredoc 是 PHP 中用来表示长字符串的语法。使用 Heredoc 语法可以避免在字符串中使用反斜杠和引号进行转义,使得长字符串的编写更加方便。

下面是 Heredoc 的基本语法:

$str = <<<EOD
    This is a long string
    that spans multiple lines
    and contains variables like $variable.
EOD;

在这个例子中,<<<EOD 告诉 PHP 接下来的字符串是一个 Heredoc 字符串,EOD 是一个标识符,用来标识 Heredoc 字符串的结束位置。在 Heredoc 字符串中,可以使用变量,并且不需要对变量进行转义。

需要注意的是,在 Heredoc 字符串中,标识符的前面不能有任何字符,包括空格和制表符。而且,标识符必须出现在行的开头,并且必须以分号结尾。

以下是一个更完整的例子,演示了如何在 Heredoc 字符串中使用变量和换行符:

$name = 'John';
$message = <<<EOD
    Hello $name,

    This is a multi-line message
    that includes variable interpolation.

    Best regards,
    ModStart
EOD;

echo $message;

输出结果如下:

Hello John,

This is a multi-line message
that includes variable interpolation.

Best regards,
ModStart

如果需要在 Heredoc 字符串中禁止变量替换,并将 $ 字符作为普通文本输出,可以在标识符 <<< 后面添加一个单引号或双引号,并将结束标识符设置为相应的引号。这种方式被称为 "Nowdoc"。

下面是一个示例,演示如何使用 Nowdoc:

$message = <<<'EOD'
    This is a message that includes $variable
    but the variable will not be replaced.

    Best regards,
    ModStart
EOD;

echo $message;

将输出

This is a message that includes $variable
but the variable will not be replaced.

Best regards,
ModStart
QQ
微信