添加到数组时,PHP命令相同吗?

ehi*_*ime 4 php arrays

只是好奇,如果这样做

$this->item['foo'] = $this->action(3);
$this->item['bar'] = $this->action(1);
$this->item['baz'] = $this->action(1);
Run Code Online (Sandbox Code Playgroud)

和做的一样

$this->item = ($this->item +
[
    'foo'  => $this->action(3),
    'bar'  => $this->action(1),
    'baz'  => $this->action(1),
]);
Run Code Online (Sandbox Code Playgroud)

如果你能解释为什么/为什么我不会感激

Bar*_*mar 8

如果$this->item已经有你指定的任何键,它们就不等同.从文档:

对于存在于两个数组中的键,将使用左侧数组中的元素,并且将忽略右侧数组中的匹配元素.

您可以通过切换参数的顺序来解决此问题:

$this->item = (
    [
    'foo'  => $this->action(3),
    'bar'  => $this->action(1),
    'baz'  => $this->action(1),
    ] + $this->item);
Run Code Online (Sandbox Code Playgroud)