我有点困惑为什么我在PHP中看到一些字符串放在单引号中,有时在双引号中。

我只知道在。net或C语言中,如果它是单引号,那就意味着它是一个字符,而不是字符串。


当前回答

在PHP中,'my name'和"my name"都是字符串。您可以在PHP手册中阅读更多关于它的内容。

你应该知道的事情

$a = 'name';
$b = "my $a"; == 'my name'
$c = 'my $a'; != 'my name'

在PHP中,人们使用单引号来定义常量字符串,如'a', 'my name', 'abc xyz',而使用双引号来定义包含标识符的字符串,如"a $b $c $d"。

还有一件事,

echo 'my name';

echo "my name";

but

echo 'my ' . $a;

echo "my $a";

字符串的其他用法也是如此。

其他回答

单引号字符串中没有解释变量。双引号字符串可以。

同样,双引号字符串可以包含不带反斜杠的撇号,而单引号字符串可以包含未转义的引号。

单引号字符串在运行时更快,因为它们不需要解析。

这两种括起来的字符都是字符串。一种类型的报价可以方便地在另一种类型的报价中附上。"'"和" " "。这两种引号类型之间最大的区别是,括起来的标识符引用替代了双引号内的标识符引用,而不是单引号内的标识符引用。

计算结果用双引号,而不是单引号:

$s = "dollars";
echo 'This costs a lot of $s.'; // This costs a lot of $s.
echo "This costs a lot of $s."; // This costs a lot of dollars.

在PHP中,'my name'和"my name"都是字符串。您可以在PHP手册中阅读更多关于它的内容。

你应该知道的事情

$a = 'name';
$b = "my $a"; == 'my name'
$c = 'my $a'; != 'my name'

在PHP中,人们使用单引号来定义常量字符串,如'a', 'my name', 'abc xyz',而使用双引号来定义包含标识符的字符串,如"a $b $c $d"。

还有一件事,

echo 'my name';

echo "my name";

but

echo 'my ' . $a;

echo "my $a";

字符串的其他用法也是如此。

PHP字符串不仅可以用两种方式指定,还可以用四种方式指定。

Single quoted strings will display things almost completely "as is." Variables and most escape sequences will not be interpreted. The exception is that to display a literal single quote, you can escape it with a back slash \', and to display a back slash, you can escape it with another backslash \\ (So yes, even single quoted strings are parsed). Double quote strings will display a host of escaped characters (including some regexes), and variables in the strings will be evaluated. An important point here is that you can use curly braces to isolate the name of the variable you want evaluated. For example let's say you have the variable $type and you want to echo "The $types are". That will look for the variable $types. To get around this use echo "The {$type}s are" You can put the left brace before or after the dollar sign. Take a look at string parsing to see how to use array variables and such. Heredoc string syntax works like double quoted strings. It starts with <<<. After this operator, an identifier is provided, then a newline. The string itself follows, and then the same identifier again to close the quotation. You don't need to escape quotes in this syntax. Nowdoc (since PHP 5.3.0) string syntax works essentially like single quoted strings. The difference is that not even single quotes or backslashes have to be escaped. A nowdoc is identified with the same <<< sequence used for heredocs, but the identifier which follows is enclosed in single quotes, e.g. <<<'EOT'. No parsing is done in nowdoc.

注: 单引号中的单引号和双引号中的双引号必须转义:

$string = 'He said "What\'s up?"';
$string = "He said \"What's up?\"";

速度: 我不认为单引号比双引号更快。他们可能在某些情况下更快。这里有一篇文章解释了自PHP 4.3以来单引号和双引号本质上一样快的一种方式(底部的无用优化,C节)。此外,这个基准测试页面有单引号和双引号的比较。大多数比较都是一样的。有一个双引号比单引号慢的比较。