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