PHP数组在使用前需要声明吗?
在编写最近的应用程序时,我不小心在声明数组之前开始填充数组。
error_reporting ( E_ALL);
$array['value'] = 'Test string';
我使用 E_ALL 错误报告并且没有抛出错误。这是正确的吗?如果是这样,声明数组值而不声明实际数组是否存在任何问题? 也许它只是不遵循良好的编程标准。
While writing a recent application I accidentally started filling an array before I had declared it.
error_reporting ( E_ALL);
$array['value'] = 'Test string';
I use E_ALL error reporting and an error was not thrown. Is this correct? And if so, are there any issues with declaring array values whilst never declaring the actual array?
Perhaps it just doesn't follow good programming standards.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
PHP 是一种弱类型语言。您的语句:
是关联数组的隐式声明(通过赋值)。因此,不会生成通知。
但是,如果您要
在分配之前编写:,那么您将收到
未定义变量
通知。PHP is a weakly typed language. Your statement:
is an implicit declaration (through assignment) of an associative array. So, a notice will not be generated.
However, if you were to write:
before an assigment, then you'll receive an
Undefined variable
notice.不,你不必这样做
,是的,声明数组以增加代码可重复性是一个好习惯
No, you don't have to
And yes, it is a good habit to declare the array to increase code redability
扩展一下,不,你“不必”这样做,但它可能是有益的。
另外,如果您关闭了 E_NOTICES,那么您将不会看到来自非未初始化变量的错误。在生产中,您应该将其关闭,但在开发中,您应该将其打开。它可以让您发现您可能看不到的问题。
To expand on that, no you do not "have" to, but it can be beneficial to.
Also if you have E_NOTICES turned OFF then you will not see errors from an non uninitialized variable. On production you should turn it off, but on development you should turn it ON. It'll allow you to find problems that you might not see.