PHP自动生存 [英] PHP autovivification

查看:99
本文介绍了PHP自动生存的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

更新:我对这个问题的初衷是确定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.

推荐答案

来自

$arr[] = value;

如果$arr尚不存在,则会创建它,因此这也是创建数组的另一种方法

If $arr doesn't exist yet, it will be created, so this is also an alternative way to create an array

以您的示例为例:

$test['a'][4] = 1;

由于$test$test['a']当前不存在;它们都被创建为数组.

Since $test and $test['a'] don't currently exist; they are both created as arrays.

$test['b'][4]['f'] = 3;

$test['b']$test['b'][4]当前不存在;它们都被创建为数组.

$test['b'] and $test['b'][4] don't currently exist; they are both created as arrays.

$test['a'][4]['f'] = 3;

$test['a'][4] 确实存在,但它是一个整数(1).这是标量值".不能用作数组.您不能在数字值上使用方括号[]语法;它不会将现有值转换为数组.

$test['a'][4] does exist, but it is an integer (1). This is the "scalar value" that cannot be used as an array. You can't use the square bracket [] syntax on number values; it doesn't convert an existing value to an array.

这篇关于PHP自动生存的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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