Search code examples
phpclassfunctionvariablesarray-push

Correct array_push usage in a class?


I have a PHP class like so:

<?php
class MyClass {
    public $my_variable = array();

    public function func1() {
        $var1 = $this->my_variable;
        array_push($var1, 'var1');
        return $this->my_variable;
    }

    public function func2() {
        $var2 = $this->my_variable;
        array_push($var2, 'var2');
        return $this->my_variable;
    }
}

$my_class = new MyClass;

print_r($my_class->func1());
print_r($my_class->func2());
?>

The two print_r functions return an empty array, and there are no errors displayed.

How can I get the "var1" and "var2" strings added to the $my_variable array? I'm not sure where I am going wrong here...!

Thanks.


Solution

  • $var1 = $this->my_variable actually creates a copy of the array, which you then push a value onto.

    Instead, you can do this: $var1 = &$this->my_variable to create a reference instead, but it would just be better to not have the pointless variable at all:

    public function func1() {
        $this->my_variable[] = 'var1';
        return $this->my_variable;
    }
    public function func2() {
        $this->my_variable[] = 'var2';
        return $this->my_variable;
    }
    

    Or, more appropriately:

    public function add($value) {
        $this->my_variable[] = $value;
        return $this->my_variable;
    }
    // call with `$my_class->add('var1'); $my_class->add('var2');