简体   繁体   English

在PHP中,有没有在使用数组之前定义数组的目的?

[英]In PHP is there any purpose to defining an array before it is used?

Consider a chunk of php code like this: 考虑这样的PHP代码块:

$example = array ( 'Location' => 'farm', 'Name' => 'billy', 'Meal' => array());
$example['Meal'] = array('Fruit' = > 'apple', 'Soup' => 'tomato', 'Drink' => 'wine');

Is there any benefit or reason to pre-define the 'Meal' sub array like that beforehand rather than simply writing: 像这样预先定义'Meal'子数组,而不是简单地编写,有什么好处或理由?

$example = array ( 'Location' => 'farm', 'Name' => 'billy');
$example['Meal'] = array('Fruit' = > 'apple', 'Soup' => 'tomato', 'Drink' => 'wine');

In short, no, unless you intend to examine the $example array between when it's created and when you add the 'Meal' sub-array. 简而言之,没有,除非您打算在创建$example到添加“ Meal”子数组之间检查$example数组。 In fact, on the 2nd line of your 1st example you're simply overwriting what you originally assigned to it. 实际上,在第一个示例的第二行上,您只是在覆盖最初分配给它的内容。

You might do it the first way if, for example, you wanted to use Array operations on the sub-array after initially creating $example . 例如,如果您想在最初创建$example之后在子数组上使用Array操作,可以采用第一种方法。 But not if you're later going to just overwrite it by assignment. 但是,如果您稍后要通过分配将其覆盖,则不会。

Not in your case, but if you want to use that variable in an array function like array_push() then it does need to be declared first. 不是您的情况,但是如果您想在数组函数(例如array_push()使用该变量,则必须先声明它。 It's always best practice to declare it if you know it's going to be an array anyway. 如果您仍然知道它将是一个数组,则始终是最佳做法。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM