字串

PHP 中的字串是一系列單位元組字元(即沒有本機 Unicode 支援),可以通過以下四種方式指定:

單引號

幾乎完全按原樣顯示事物。變數和大多數轉義序列都不會被解釋。例外情況是,要顯示文字單引號,可以使用反斜槓轉義它,並顯示反斜槓,可以使用另一個反斜槓轉義它

$my_string = 'Nothing is parsed, except an escap\'d apostrophe or backslash. $foo\n';
var_dump($my_string);

/*
string(68) "Nothing is parsed, except an escap'd apostrophe or backslash. $foo\n"
*/

雙引號

與單引號字串不同,將評估字串中的簡單變數名稱和轉義序列 。大括號(如上例所示)可用於隔離複雜的變數名稱。

$variable1 = "Testing!";
$variable2 = [ "Testing?", [ "Failure", "Success" ] ];
$my_string = "Variables and escape characters are parsed:\n\n";
$my_string .= "$variable1\n\n$variable2[0]\n\n";
$my_string .= "There are limits: $variable2[1][0]";
$my_string .= "But we can get around them by wrapping the whole variable in braces: {$variable2[1][1]}";
var_dump($my_string);

/*
string(98) "Variables and escape characters are parsed:

Testing!

Testing?

There are limits: Array[0]"

But we can get around them by wrapping the whole variable in braces: Success

*/

定界符

在 heredoc 字串中,變數名和轉義序列的解析方式與雙引號字串類似,但大括號不適用於複雜的變數名。字串的開頭由 <<< identifier 分隔,結尾由 identifier 分隔,其中 identifier 是任何有效的 PHP 名稱。結束識別符號必須單獨出現在一行中。在識別符號之前或之後不允許使用空格,儘管與 PHP 中的任何行一樣,它也必須以分號結束。

$variable1 = "Including text blocks is easier";
$my_string = <<< EOF
Everything is parsed in the same fashion as a double-quoted string,
but there are advantages. $variable1; database queries and HTML output
can benefit from this formatting.
Once we hit a line containing nothing but the identifier, the string ends.
EOF;
var_dump($my_string);

/*
string(268) "Everything is parsed in the same fashion as a double-quoted string,
but there are advantages. Including text blocks is easier; database queries and HTML output
can benefit from this formatting.
Once we hit a line containing nothing but the identifier, the string ends."
*/

Nowdoc

nowdoc 字串就像 heredoc 的單引號版本,儘管甚至不評估最基本的轉義序列。字串開頭的識別符號用單引號括起來。

PHP 5.x >= 5.3

$my_string = <<< 'EOF'
A similar syntax to heredoc but, similar to single quoted strings,
nothing is parsed (not even escaped apostrophes \' and backslashes \\.)
EOF;
var_dump($my_string);

/*
string(116) "A similar syntax to heredoc but, similar to single quoted strings,
nothing is parsed (not even escaped apostrophes \' and backslashes \\.)"
*/