Scarass Scarass - 24 days ago 10
PHP Question

Class member reference to another object in PHP

First code and then the question:

class MyArray
{
private $arrayRef;

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

function addElement($newElement){
$this->arrayRef[] = $newElement;
}

function print(){
print_r($this->arrayRef);
}
}

$array = ['first', 'second'];
$arrayObject = new MyArray($array);
$arrayObject->addElement('third');

print_r($array); // prints array containing 2 elements
echo '<br/>';
$arrayObject->print(); // prints array containing 3 elements


Class member $arrayRef, in this example doesn't work as a reference to another array provided in constructor. Argument in constructor is passed by reference, but I guess that doesn't make member $arrayRef also a reference to that array as well.

Why doesn't it work like that and how to make it work?

If you still don't get what I mean: first print_r prints array containing 2 elements, even thought it may be expected to contain 3.
When I pass third element to $arrayObject via addElement() I also want it to be added in the $array that I passed to constructor of class.

Answer

The answer is actually quite simple. Yes, you pass the array by reference via &$array but this reference gets lost when you assign/copy it to the member variable. To keep the reference, you can use the =& operator like so

$this->arrayRef =& $array;

See it work in this fiddle. You can read more about it in this question/answer (just look for reference).

Beware not to use &= (which does a bitwise operation) instead of =& (which assigns by reference).

Comments