字符串

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 \\.)"
*/