为什么 PHP 数组示例要留下尾随逗号? [英] Why do PHP Array Examples Leave a Trailing Comma?

查看:26
本文介绍了为什么 PHP 数组示例要留下尾随逗号?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我见过如下例子:

$data = array(
   'username' => $user->getUsername(),
   'userpass' => $user->getPassword(),
   'email' => $user->getEmail(),
);

然而,实际上我总是留下尾随逗号.我做错了什么,还是这只是另一种"做事方式?如果我使用的是框架,尾随逗号不会对代码生成产生负面影响吗?我也看到过在其他语言(Java、C++)的数组声明中使用尾随逗号,所以我认为保留尾随逗号的原因并非特定于 PHP,但这激起了我的兴趣.

However, in practice I have always not left the trailing comma. Am I doing something wrong, or is this just 'another' way of doing it? If I was using a framework would not having the trailing comma affect code generation negatively? I have seen the use of trailing commas in array declarations in other languages (Java, C++) as well, so I assume the reasons for leaving trailing commas are not specific to PHP, but this has piqued my interest.

推荐答案

为什么 PHP 数组示例要留下尾随逗号?

Why do PHP Array Examples Leave a Trailing Comma?

因为他们可以.:) PHP 数组手册条目 指出:

Because they can. :) The PHP Manual entry for array states:

在最后一个定义的数组条目后有一个尾随逗号,虽然不常见,但是一种有效的语法.

Having a trailing comma after the last defined array entry, while unusual, is a valid syntax.

说真的,这完全是为了方便,这样您就可以轻松地将另一个元素添加到数组中,而无需先将尾随逗号添加到最后一个条目中.

Seriously, this is entirely for convenience so you can easily add another element to the array without having to first add the trailing comma to the last entry.

说到其他语言:在 JavaScript 中要小心这一点.一些较旧的浏览器会抛出错误,但较新的浏览器通常允许.

Speaking of other languages: Be careful with this in JavaScript. Some older browsers will throw an error, though newer ones generally allow it.

这篇关于为什么 PHP 数组示例要留下尾随逗号?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆