Tell me more ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

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.

share|improve this question

2 Answers

up vote 2 down vote accepted

$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');
share|improve this answer
People use such pointless variables to shorten the $var. – bwoebi Apr 21 at 20:46
1  
@bwoebi: People interested in short code don't use array_push... :P – rynah Apr 21 at 20:48
@minitech People who don't know about [] use array_push ^^ – bwoebi Apr 21 at 20:54
I dont think I've ever used array_pop, ever, in 10ish years of writing php. But I also find that people who dont even know about array_push (regardless if they use it) also never know about array_pop and array_shift and array_unshift – Uberfuzzy Apr 21 at 21:24

You have to assign the $var's by reference. You copy the array and then add to the copy some entry and then return the initial array.

$var2 = &$this->my_variable;

would be right. The & is marking here a reference.

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.