PHP class does not save link

How to pass a link to the constructor of an object and allow this object to update this link?

class A{ private $data; function __construct(&$d){ $this->data = $d; } function addData(){ $this->data["extra"]="stuff"; } } // Somewhere else $arr = array("seed"=>"data"); $obj = new A($arr); $obj->addData(); // I want $arr to contain ["seed"=>"data", "extra"=>"stuff"] // Instead it only contains ["seed"=>"data"] 
+6
source share
3 answers

You should store it everywhere as a link.

 function __construct (&$d) { $this->data = &$d; // the & here } 
+11
source

You need to tell PHP to assign the link also to the private data member as follows:

 $this->data = &$d; 

Depending on the context, you may not use references to external arrays, and it may be better to have this array inside the object that processes it.

Aslo note that the constructor is called __construct not __construction .

+2
source

This will do what you ask for:

 class Test { private $storage; public function __construct(array &$storage) { $this->storage = &$storage; } public function fn() { $this->storage[0] *= 10; } } $storage = [1]; $a = new Test($storage); $b = new Test($storage); $a->fn(); print_r($a); // $storage[0] is 10 print_r($b); // $storage[0] is 10 $b->fn(); print_r($a); // $storage[0] is 100 print_r($b); // $storage[0] is 100 

Alternative 1

Instead of using an array, you can also use ArrayObject , ArrayIterator or SplFixedArray . Since these are objects, they will be passed by reference. They all implement ArrayAccess so that you can access them through square brackets, e.g.

 $arrayObject = new ArrayObject; $arrayObject['foo'] = 'bar'; echo $arrayObject['foo']; // prints 'bar' 

Alternative 2

Instead of using a generic type, use a special type. Find out what you are storing in this array. Is this a Config ? A Registry ? A UnitOfWork ? Find out what it really is. Then make it an object and give it an API that reflects responsibilities. Then enter this object and access it through this API.

See this article by Martin Fowler for some tips on how to make type

+1
source

All Articles