PHP数组在使用前需要声明吗?

发布于 2024-09-18 14:29:32 字数 208 浏览 5 评论 0原文

在编写最近的应用程序时,我不小心在声明数组之前开始填充数组。

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

天邊彩虹 2024-09-25 14:29:32

在撰写最近的申请时,我
不小心开始填充数组
在我宣布之前。

PHP 是一种弱类型语言。您的语句:

$array['value'] = 'Test string';

是关联数组的隐式声明(通过赋值)。因此,不会生成通知。

但是,如果您要

echo $array['value'];

在分配之前编写:,那么您将收到未定义变量通知。

While writing a recent application I
accidentally started filling an array
before I had declared it.

PHP is a weakly typed language. Your statement:

$array['value'] = 'Test string';

is an implicit declaration (through assignment) of an associative array. So, a notice will not be generated.

However, if you were to write:

echo $array['value'];

before an assigment, then you'll receive an Undefined variable notice.

鲸落 2024-09-25 14:29:32

不,你不必这样做

,是的,声明数组以增加代码可重复性是一个好习惯

No, you don't have to

And yes, it is a good habit to declare the array to increase code redability

风吹过旳痕迹 2024-09-25 14:29:32

扩展一下,不,你“不必”这样做,但它可能是有益的。

另外,如果您关闭了 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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文