PHP Heredoc 语法

Sheeraz Gul 2024年2月15日
PHP Heredoc 语法

heredoc 语法用于在 PHP 中声明字符串。本教程描述并演示了在 PHP 中使用 heredoc 语法。

PHP Heredoc 语法

在 PHP 中,程序员大多使用两种方法来声明字符串,一种是用' ' 单引号,另一种是用"" 双引号,如下所示。

$DemoString = 'Demo String';

$DemoString = "Demo String";

heredoc 语法是在 PHP 中声明字符串的另一种方式。heredoc 语法至少需要三行代码,它在开头使用 <<< 运算符来声明字符串变量。

此方法的语法是:

$DemoString = <<< identifier
// string
// string
// string
identifier;

标识符用于语法的开头和结尾。你可以在此处使用任何词来代替标识符

以下是使用 heredoc 语法时的一些要点。

  1. heredoc 变量必须至少有三行以 <<< 和一个标识符开头,并以相同的标识符结尾。
  2. HTML 标签也可以用在 heredoc 语法中,将实现为 HTML 元素。
  3. 永远不要尝试在 heredoc 语法中添加函数和条件。这将产生错误。
  4. 要在 heredoc 语法中显示其他变量,你可以使用花括号 {}

让我们尝试一个例子。

<?php
$DemoString = <<<Delftstack
Hello This is the Employee List from Delftstack.com<br>
1. Jack<br>
2. Michelle<br>
3. Jhonny<br>
4. Dana <br>
5. Natasha.
Delftstack;
echo $DemoString;
?>

上面的代码使用带有标识符 Delftstack 的 heredoc 语法。见输出:

Hello This is the Employee List from Delftstack.com
1. Jack
2. Michelle
3. Jhonny
4. Dana
5. Natasha.

这是另一个带有 HTML 标记和其他变量的示例。

<?php
$SiteName = "Delftstack";
$Message = "This is the best tutorials site for programmers";
$Print = <<<heredocDelftstack
<div >
    <div >
        <h1>{$SiteName}</h1>
        <p>{$Message}</p>
    </div>
</div>
heredocDelftstack;
echo $Print;
?>

上面的代码将以 HTML 形式显示数据。见输出:

Heredoc HTML

作者: Sheeraz Gul
Sheeraz Gul avatar Sheeraz Gul avatar

Sheeraz is a Doctorate fellow in Computer Science at Northwestern Polytechnical University, Xian, China. He has 7 years of Software Development experience in AI, Web, Database, and Desktop technologies. He writes tutorials in Java, PHP, Python, GoLang, R, etc., to help beginners learn the field of Computer Science.

LinkedIn Facebook