在字符串问题中简单的php Dollar $评价

7 php

我一直很困惑.e,g在php我有sql语句

$qry = "select * from table where id = $id";
Run Code Online (Sandbox Code Playgroud)

现在可以直接在引号内插入"$"或者我必须使用

 $qry = "select * from table where id =".$id." ";
Run Code Online (Sandbox Code Playgroud)

要么

 $qry = 'select * from table where id = $id';
Run Code Online (Sandbox Code Playgroud)

要么

 $qry = 'select * from table where id = '$id'';
Run Code Online (Sandbox Code Playgroud)

哪个是对的

dec*_*eze 4

如果字符串包含在双引号中,则将对变量进行求值。如果它用单引号括起来,那么它就是字面意思,您将得到与您键入的内容完全相同的内容。

$bar = 42;
'Foo $bar Baz'           // Foo $bar Baz
"Foo $bar Baz"           // Foo 42 Baz
'Foo ' . $bar . ' Baz'   // Foo 42 Baz
'Foo ' . '$bar' . ' Baz' // Foo $bar Baz
"$bar " . $bar . " $bar" // 42 42 42    
Run Code Online (Sandbox Code Playgroud)

以下是相关手册部分的完整说明:
http://php.net/manual/en/language.types.string.php#language.types.string.parsing

要将实际的引号放入字符串中,您需要替换它们或转义它们。

'"$bar"'    // "$bar"
"'$bar'"    // '42'
'\'$bar\''  // '$bar'
"\"$bar\""  // "42"
''$bar''    // syntax error, empty string '' + $bar + empty string ''
Run Code Online (Sandbox Code Playgroud)

还有他说的话