不带引号PHP数组访问 [英] PHP Array access without quotes
问题描述
我敲到一个现象,在现有的PHP源代码,
有没有这样的撇号字段访问:$ _ GET [测试]
I knocked to a phenomenon in an existing php source, with field access without apostrophe like this: $_GET[test].
我不确定,也不知道,这是一个可能的方式,
所以我写了一个简单的例子来进行测试:
I got unsure, also don't know, that this is a possible way, so I wrote a short example for testing:
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)。
And it works, every result got the value (ArrayValue).
我preFER样病例的访问方法2.
I prefer the access method like case 2.
时的情况下,3正常的,允许编码风格在PHP?
Is case 3 a normal, allowed coding style in php?
推荐答案
在这里会发生什么事,是PHP看到的恒定名为测试
。如果定义常量,则返回其值,它是没有定义,PHP回落到字符串测试
。例如:
What happens here, is that PHP sees a constant called test
. If the constant is defined, the value is returned, it isn't defined, PHP falls back to the string "test"
. For example:
$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".
这是为了向下兼容,你永远不应该使用它。如果你打开声明,你会看到PHP抱怨关于它。
It's for backwards compatibility and you should never use it. If you'll turn on notices, you'll see that PHP complains about it.
这篇关于不带引号PHP数组访问的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!