在PHP中使用array [key]可以吗? [英] Is it okay to use array[key] in PHP?
问题描述
可以使用不带单引号或双引号的数组,例如$ array [key]吗?我认为这很糟糕,因为如果我不使用单引号或双引号,PHP首先会寻找常量.我的一位同事告诉我,没关系.
Is it okay to use array without single or double quotion like $array[key]? I thought it is bad because PHP look for constant first if I don't use single or double quotation. One of my colleagues told me that it does not matter.
你们怎么看?
推荐答案
即使在大多数情况下都可以正常使用,它也不被认为是正确的.
基本上,当PHP看到此信息时:
Basically, when PHP sees this :
echo $array[key];
它将搜索用 define
定义的常量,称为 key
;如果没有,则采用'key'
值.
It will search for a constant, defined with define
, called key
-- and, if there is none, if will take the 'key'
value.
但是,如果您的代码前面有这样的内容:
But, if there is something like this earlier in your code :
define('key', 'glop');
不需要
echo $array['key'];
了;相反,它将使用 key
常量的值-您的代码将与:
anymore ; instead, it'll use the value of the key
constant -- and your code will be the same as :
echo $array['glop'];
最后,至少有两个原因,不把引号引起来是不好的:
In the end, not putting quotes arround the key's name is bad for at least two reasons :
- 它可能无法达到您的期望,这很危险-这是非常糟糕的
- 今天可能会...
- 但是下周/月/年呢?
- 也许有一天,您会
define
一个名称为错误的常量;-)
- There is a risk that it will not do what you expect -- which is very bad
- It might, today...
- But what about next week / month / year ?
- Maybe, one day, you'll
define
a constant with the wrong name ;-)
- 在使用
'key'
之前,它必须搜索一个常量.
- 而且,如评论中所述,它会生成通知(即使您禁用
display_errors
,即使以后将其丢弃,仍然会生成通知/警告/错误)
- it has to search for a constant, before using
'key'
- And, as said in a comment, it generates notices (even if you disable
error_reporting
anddisplay_errors
, the notices/warnings/errors are still generated, even if discarded later)
所以:在这一点上,您不应该听那个家伙的话:他错了:这很重要.
So : you should not listen to that guy on this point : he is wrong : it does matter.
并且,如果您需要某种证明",而证明"比人们在堆栈溢出方面所能告诉您的要好,则可以将他指向手册的本部分,作为参考:
And if you need some "proof" that's "better" than what people can tell you on stackoverflow, you can point him to this section of the manual, as a reference : Why is $foo[bar] wrong?这篇关于在PHP中使用array [key]可以吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!