Search code examples
phpfunctionarray-merge

Failed Using array_merge inside of PHP class


class Test
{
  public $data = array();

  public function addData($data = array())
  {
    array_merge($data, $this->data);
    return $this;
  }

  public function showData()
  {
    print_r($this->data);
  }
}
$test = new Test;
$test->addData(array("halo", "zaki"))->showData();

i tried to merging 2 array, but it doesn't work, maybe someone can explain to me?


Solution

  • You forgot to assign the resulting array to member variable $data. It should be,

    $this->data = array_merge($data, $this->data);