PHP Array access without quotes

混江龙づ霸主 提交于 2019-12-23 07:59:08

问题


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>";

And it works, every result got the value (ArrayValue).

I prefer the access method like case 2.

Is case 3 a normal, allowed coding style in php?


回答1:


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".

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.




回答2:


If you don't put the key into quotes, it will be handled as an undefined constant (assuming it is not defined anywhere), which may work for now, but can fail in future PHP versions. Therefor it is just wrong and the PHP documentation states this variant also as wrong. Check out 'Arrays do's and don'ts'.

By the way: If you put the key into double quotes, it renders variables inside to the key-name.




回答3:


Using array key names without quotes is a legacy feature in PHP. It was originally the way to do it, but it is no longer recommended and is only still supported for backward compatibility. It will throw a warning message if you have strict mode enabled.

The reason it works is that it sees the key name in this form as a constant. When PHP sees an unknown constant, it defaults to the name of the constant as the value, hence it works as a string replacement.

It would break if you had define() elsewhere in your program that set the value of that constant. It also doesn't work if your key name contains spaces, starts with a digit, or is an invalid constant name for any other reason.

For these reasons, it is not recommended to use this method.

But most of all, the PHP developers have stated publicly that it is not good practice, which may well mean that future PHP versions remove the ability to write code like this.



来源:https://stackoverflow.com/questions/13622486/php-array-access-without-quotes

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!