我在现有的 php 源代码中发现了一个现象, 像这样不带撇号的字段访问:$_GET[test].
我不确定,也不知道这是一种可能的方式, 所以我写了一个简短的测试示例:
echo "Array Test, fields without apostrophe, like \$_GET[fieldname]<BR><BR>";
$a = array();
$a['test'] = "ArrayValue";
echo "case 1 -> \$a['test']: " . $a['test'] . "<BR>";
echo "case 2 -> \$a[\"test\"]: " . $a["test"] . "<BR>";
echo "case 3 -> \$a[test]: " . $a[test] . "<BR>";
它起作用了,每个结果都得到了值 (ArrayValue)。
我更喜欢case 2的访问方式。
情况 3 是 php 中允许的正常编码风格吗?
最佳答案
这里发生的是 PHP 看到了 a constant称为测试
。如果定义了常量,则返回值,如果没有定义,PHP 会回退到字符串 "test"
。例如:
$array = array("A" => "Foo", "B" => "Bar", "C" => "Baz")
define("B", "C");
echo $array[A]; // The constant "A" is undefined,
// so PHP falls back to the string "A",
// which has the value "Foo".
echo $array["B"]; // The result is "Bar".
echo $array[B]; // The value of constant "B" is the string "C".
// The result is "Baz".
它是为了向后兼容,你不应该使用它。如果你愿意 turn on notices ,您会看到 PHP 会提示它。
关于不带引号的 PHP 数组访问,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13622486/