PHP - Heredoc & Nowdoc



PHP 提供了兩種替代方案,用於以 **heredoc** 和 **nowdoc** 語法宣告單引號或雙引號字串。

  • 單引號字串不解釋跳脫字元,也不擴充套件變數。

  • 另一方面,如果您宣告一個包含雙引號字元本身的雙引號字串,則需要使用“\”符號對其進行轉義。**heredoc** 語法提供了一種便捷的方法。

PHP 中的 Heredoc 字串

PHP 中的 heredoc 字串非常類似於雙引號字串,但沒有雙引號。這意味著它們不需要轉義引號並擴充套件變數。

Heredoc 語法

$str = <<<IDENTIFIER
place a string here
it can span multiple lines
and include single quote ' and double quotes "
IDENTIFIER;

首先,以“<<<”運算子開頭。在此運算子之後,提供一個識別符號,然後換行。字串本身緊隨其後,然後是相同的識別符號以關閉引號。字串可以跨越多行,幷包含單引號(')或雙引號(")。

結束識別符號可以透過空格或製表符縮排,在這種情況下,縮排將從文件字串中的所有行中去除。

示例

識別符號只能包含字母數字字元和下劃線,並且必須以下劃線或非數字字元開頭。結束識別符號除了分號(;)之外不應包含任何其他字元。此外,結束識別符號之前和之後必須只有換行符。

請看下面的例子 -

<?php  
   $str1 = <<<STRING
   Hello World
      PHP Tutorial
         by TutorialsPoint
   STRING;

   echo $str1;
?>

它將產生以下 **輸出** -

Hello World
    PHP Tutorial
        by TutorialsPoint

示例

結束識別符號在編輯器中的第一列之後可以包含或不包含縮排。如有任何縮排,都將被刪除。但是,結束識別符號的縮排不能超過主體中的任何行。否則,將引發 ParseError。請看下面的例子及其輸出 -

<?php  
   $str1 = <<<STRING
   Hello World
      PHP Tutorial
   by TutorialsPoint
         STRING;
         
   echo $str1;
?>

它將產生以下 **輸出** -

PHP Parse error:  Invalid body indentation level 
(expecting an indentation level of at least 16) in hello.php on line 3

示例

heredoc 中的引號不需要轉義,但仍然可以使用 PHP 轉義序列。Heredoc 語法還會擴充套件變數。

<?php  
   $lang="PHP";
   echo <<<EOS
   Heredoc strings in $lang expand vriables.
   The escape sequences are also interpreted.
   Here, the hexdecimal ASCII characters produce \x50\x48\x50
   EOS;
?>

它將產生以下 **輸出** -

Heredoc strings in PHP expand vriables.
The escape sequences are also interpreted.
Here, the hexdecimal ASCII characters produce PHP

PHP 中的 Nowdoc 字串

PHP 中的 nowdoc 字串類似於 heredoc 字串,只是它不擴充套件變數,也不解釋轉義序列。

<?php  
   $lang="PHP";

   $str = <<<'IDENTIFIER'
   This is an example of Nowdoc string.
   it can span multiple lines
   and include single quote ' and double quotes "
   IT doesn't expand the value of $lang variable
   IDENTIFIER;

   echo $str;
?>

它將產生以下 **輸出** -

This is an example of Nowdoc string.
it can span multiple lines
and include single quote ' and double quotes "
IT doesn't expand the value of $lang variable

nowdoc 的語法類似於 heredoc 的語法,只是“<<<”運算子後面的識別符號需要用單引號括起來。nowdoc 的識別符號也遵循 heredoc 識別符號的規則。

Heredoc 字串就像沒有轉義的雙引號字串。Nowdoc 字串就像沒有轉義的單引號字串。

廣告