0

I have built a function to retrieve the last specified key of an array, it references the array and displays it fine, however, when I try to add to the reference variable, it does not affect the referenced array.

Here is my code:

class test {
    public function __construct() {
        // For testing
        $this->keys[] = 'key1';
        $this->keys[] = 'key2';
        $this->array['key1']['key2'] = 'Hello World';
    }
    protected function &getArray() {
        $array = &$this->array;
        foreach($this->keys as $key) {
            $array = &$array[$key];
        }
        return $array;
    }
    function add() {
        $tmpArray = $this->getArray();
        print_r($tmpArray);
        echo "<br>\n";
        $tmpArray = 'Goodbye World';
        print_r($tmpArray);
        echo "<br>\n";
        print_r($this->array);
    }

}

$test = new test;
$test->add();

To sum it up, add() and __construct() are for testing. I am trying to add to $this->array with add(). However when I specify $tmpArray = 'Goodbye World' the referenced array $this->array['key1']['key2'] is still Hello World.

Could someone help point me in the right direction?

4
  • Err.. what does your class achieve? I am confused.. Commented Dec 5, 2013 at 23:26
  • This is mostly a testing class. The most important part is getArray() which references the 'key2' of $this->array since key2 is the last specified in $this->keys. $tmpArray is equal to Hello World from the reference before I set it to Goodbye World. But I am trying to get $this->array['key1']['key2'] to equal Goodbye World too from the reference. Commented Dec 5, 2013 at 23:31
  • Where does $tags exist in the class variables, where does $values exist in the class variables, you must be getting errors? I can't see any variable declarations inside test. Commented Dec 5, 2013 at 23:33
  • My fault, that was a bad copy. It should have been keys, and values should have been array. It has been fixed now. Commented Dec 5, 2013 at 23:37

1 Answer 1

1

In order to return references in PHP, you need to use & twice, once in the definition and once more in assignment. You're missing the one in assignment:

$tmpArray = &$this->getArray();

See PHP: Returning References for details and please don't ask why as I'm incapable of generating rationale for PHP behaviour.

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you, I thought I had tried that but apparently not, but it does indeed work.

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.