initial commit
[m6w6/m6w6.github.io] / _posts / 2006-08-21-get-and-array-rumors.md
1 ---
2 title: __get() and array rumors
3 author: m6w6
4 tags:
5 - PHP
6 ---
7
8 There've been lots of rumors about overloaded array properties lately.
9
10 The following code
11 ```php
12 class funky {
13 private $p = array();
14 function __get($p) {
15 return $this->p;
16 }
17 }
18 $o = new funky;
19 $o->prop["key"] = 1;
20 ```
21
22 will yield:
23
24 ```shell
25 Notice: Indirect modification of overloaded property funky::$p has no effect
26 ```
27
28 As arrays are the only complex types that are passed by value (resources don't
29 really count here) the solution to described problem is simple: use an object;
30 either an instance of stdClass or ArrayObject will do well, depending if you
31 want to use array index notation.
32
33 So the folloiwng code will work as expected, because the ArrayObject instance
34 will pe passed by handle:
35
36 ```php
37 class smarty {
38 private $p;
39 function __construct() {
40 $this->p = new ArrayObject;
41 }
42 function __get($p) {
43 return $this->p;
44 }
45 }
46 $o = new smarty;
47 $o->prop["key"] = 1;
48 ```
49
50 I guess most of you already knew, but anyway... ;)
51