将引号放在PHP命名索引上是不必要的?

GTS*_*Joe -2 php arrays indexed

以下是:

$arr = [
    foo => 'bar',
    bar => 'foo'
];
Run Code Online (Sandbox Code Playgroud)

同样如下:

$arr = [
    'foo' => 'bar',
    'bar' => 'foo'
];
Run Code Online (Sandbox Code Playgroud)

换句话说,是否不需要在命名索引上加引号?什么时候才真正需要在字符串索引上引用引号?

Jim*_*ght 6

你的第一个例子应该发出通知.如果您不使用引号,那么PHP将查找具有该名称的常量.

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
Run Code Online (Sandbox Code Playgroud)

我在PHP 7.1.8中运行了这个示例,但是在PHP 7.2中,这已被弃用.

  • 这只是PHP 7.1及更早版本中的通知(不是错误)和PHP 7.2中的警告.[有人建议完全在PHP 8中弃用这种行为](https://wiki.php.net/rfc/deprecate-bareword-strings). (4认同)