如何在 php 中向 class 属性 数组添加项目?

How to add items to class property array in php?

我有一个 class 属性,它是一个数组。我有一些 $data 数组,我想在不使用 foreach 循环的情况下将其添加到该数组中。

查看示例代码:

<?php
    class A {
    public $y = array();
    public function foo() {
        $data = array('apples', 'pears', 'oranges');
        array_merge($this->y, $data);
    }
}

$a = new A();
$a->foo();
print_r($a->y);
assert(sizeof($a->y)==3);

预期结果:

Array (
    [0] => apples
    [1] => pears
    [2] => oranges
)

实际结果:

Array ( )
PHP Warning:  assert(): Assertion failed on line 16

修改函数定义如下:

public function foo() {
        $data = array('apples', 'pears', 'oranges');
        $this->y = array_merge($this->y, $data);
}

documentation 明确指出返回合并后的数组。所以,传入参数的原始数组保持不变。