1

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.

2 Answers 2

4

$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');
Sign up to request clarification or add additional context in comments.

3 Comments

@bwoebi: People interested in short code don't use array_push... :P
@minitech People who don't know about [] use array_push ^^
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
1

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.