Is Putting Quotes on PHP Named Indexes Unnecessary?

徘徊边缘 提交于 2019-12-13 09:25:40

问题


Is the following:

$arr = [
    foo => 'bar',
    bar => 'foo'
];

The same as:

$arr = [
    'foo' => 'bar',
    'bar' => 'foo'
];

In other words, is putting quotes on named indexes unnecessary? When would be the only times when putting quotes on string indexes be really needed?


回答1:


Your first example should throw a NOTICE. If you do not use quotes then PHP will look for a constant with that name.

php > $myArr = [abc => 'hello'];
PHP Notice:  Use of undefined constant abc - assumed 'abc' in php shell code on line 1
PHP Stack trace:
PHP   1. {main}() php shell code:0

Notice: Use of undefined constant abc - assumed 'abc' in php shell code on line 1

Call Stack:
    9.7779     350840   1. {main}() php shell code:0

I ran this example in PHP 7.1.8, however in PHP 7.2 this has been deprecated.




回答2:


PHP converts "bare strings" into proper strings, but will give you a warning. It is likely that this functionality will disappear in future.

If you really, really want to do this (you shouldn't), it will work as log as the string matches the format for a constant, which is the regex

[a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*

(Don't do it. Just don't.)



来源:https://stackoverflow.com/questions/49365907/is-putting-quotes-on-php-named-indexes-unnecessary

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