PHP自动生存 [英] PHP autovivification
问题描述
更新:我对这个问题的初衷是确定PHP是否实际上具有此功能.这已经失去了答案对标量问题的关注.请改为查看以下新问题:"PHP是否具有自动生存能力?" 参考.
Update: My original intention for this question was to determine if PHP actually has this feature. This has been lost in the answers' focus on the scalar issue. Please see this new question instead: "Does PHP have autovivification?" This question is left here for reference.
根据Wikipedia ,PHP没有自动生存功能,但是此代码有效:/p>
According to Wikipedia, PHP doesn't have autovivification, yet this code works:
$test['a']['b'] = 1;
$test['a']['c'] = 1;
$test['b']['b'] = 1;
$test['b']['c'] = 1;
var_dump($test);
输出:
array
'a' =>
array
'b' => int 1
'c' => int 1
'b' =>
array
'b' => int 1
'c' => int 1
我发现此代码也适用:
$test['a'][4] = 1;
$test['b'][4]['f'] = 3;
但是添加这一行会引起警告(警告:不能将标量值用作数组")
But adding this line causes an warning ("Warning: Cannot use a scalar value as an array")
$test['a'][4]['f'] = 3;
这是怎么回事?为什么在索引之后添加关联元素时它失败?这是像Perl一样的真正"自动生存,还是它的某种变体,还是其他?
What's going on here? Why does it fail when I add the associative element after the index? Is this 'true' Perl-like autovivification, or some variation of it, or something else?
哦,我现在看到标量的错误,哎呀!这些工作按预期进行:
oh, I see the error with the scalar now, oops! These work as expected:
$test['a'][4]['a'] = 1;
$test['a'][4]['b'] = 2;
$test['a'][5]['c'] = 3;
$test['a'][8]['d'] = 4;
那么,php是否具有自动生存能力?在Google中搜索"php autovivification"并不会给出一个规范的答案或示例.
So, php does have autovivification? Searching Google for "php autovivification" doesn't bring up a canonical answer or example of it.