Reference problem when returning an object from array in PHP

Posted by avastreg on Stack Overflow See other posts from Stack Overflow or by avastreg
Published on 2010-05-12T13:00:25Z Indexed on 2010/05/12 13:04 UTC
Read the original article Hit count: 156

Filed under:
|
|
|

I've a reference problem; the example should be more descriptive than me :P

I have a class that has an array of objects and retrieve them through a key (string), like an associative array:

class Collection {

    public $elements;

    function  __construct() {
        $this->elements = array();
    }

    public function get_element($key) {

        foreach($this->elements as $element) {
            if ($element->key == $key) {

                return $element;
                break;
            }
        }
        return null;

    }

    public function add_element ($element) {
        $this->elements[] = $element;
    }

}

Then i have an object (generic), with a key and some variables:

class Element {

    public $key;
    public $another_var;

    public function __construct($key) {
        $this->key = $key;
        $this->another_var = "default";
    }
}

Now, i create my collection:

$collection = new Collection();

$collection->add_element(new Element("test1"));
$collection->add_element(new Element("test2"));

And then i try to change variable of an element contained in my "array":

$element = $collection->get_element("test1");
$element->another_var = "random_string";
echo $collection->get_element("test1")->another_var;

Ok, the output is

random_string

so i know that my object is passed to $element in reference mode.

But if i do, instead:

$element = $collection->get_element("test1"); $element = null; //or $element = new GenericObject(); $element->another_var = "bla"; echo $collection->get_element("test1")->another_var;

the output is

default

like if it lost the reference.

So, what's wrong? I have got the references to the variables of the element and not to the element itself?

Any ideas?

© Stack Overflow or respective owner

Related posts about php

Related posts about array