Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using __set with arrays solved, but why?

Having done a bit of research, I eventually came across the answer to a question I was soon to ask here anyways; How do you work with arrays via the __get and __set magic methods in PHP? Whenever I was trying to set a value using something like $object->foo['bar'] = 42; it seemed to silently discard it.

Anyways, the answer is simple; The __get method simply needs to return by reference. And after tossing an ampersand in front of it, sure enough it works.

My question actually, is why? I can't seem to understand why this is working. How does __get returning by reference affect __set working with multidimensional arrays?

Edit: By the way, running PHP 5.3.1

like image 258
Dan Lugg Avatar asked Nov 30 '10 04:11

Dan Lugg


1 Answers

In PHP when you return a value from a function you can consider it making a copy of that value (unless it's a class). In the case of __get unless you return the actual thing you want to edit, all the changes are made to a copy which is then discarded.

like image 87
Kendall Hopkins Avatar answered Sep 30 '22 18:09

Kendall Hopkins