如何在php中的类属性数组中添加项?

时间:2016-07-18 14:35:46

标签: php arrays properties array-merge

我有一个类属性,它是一个数组。我有一些$ 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

1 个答案:

答案 0 :(得分:2)

按如下方式更改功能定义:

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

documentation清楚地表明返回合并的数组。因此,参数中传递的原始数组保持不变。