在$_POST变量中使用引号、撇号或两者都不使用有什么区别


What is the difference in using quotes, apostrophes or neither in $_POST variables?

我最近发布了一个问题,其中代码不起作用,有人建议我在$_POST变量中添加撇号。

我在用

$_POST[variable]

人们(?)推荐

$_POST['variable']

PHP.net推荐

$_POST["variable"]

你用什么,为什么
使用其中一个会产生什么差异?

使用"'之间没有实质性差异。数组键可以是整数,也可以是字符串。字符串在PHP中引用。在这种情况下不使用引号是可行的,但PHP首先检查键是否为常量,然后将其解释为字符串。PHP文档中不鼓励不引用数组键。

第一个方法将抛出一个Notice:

[18-Feb-2013 02:46:06] PHP Notice:  Use of undefined constant variable - assumed 'variable' in /Users/Aram/Development/Web/test.php on line 6

此外,你不能有连字符,因为它会单独处理它们。

[18-Feb-2013 02:46:56] PHP Notice:  Use of undefined constant variable - assumed 'variable' in /Users/Aram/Development/Web/test.php on line 6
[18-Feb-2013 02:46:56] PHP Notice:  Use of undefined constant name - assumed 'name' in /Users/Aram/Development/Web/test.php on line 6

使用单引号,因为它比双引号更简单,而且不需要使用移位键。

这与$_POST变量无关
它是关于字符串的。字符串作为数组键是严格的。

这里有字符串作为数组键,所以必须将它们格式化为字符串
要格式化字符串,可以使用任意引号,没有区别。

没有引号的variable实际上是一个常量

唯一需要省略引号的情况是双引号字符串:

echo "Hello $_GET[name], howdy?";

如果variable是常量或变量的名称,则使用$_POST[variable]:$var。

使用$_POST["variable"]$_POST['variable'] if变量`是一个字符串。

相关文章: