php magic __set and __get

Last days I have a problem with php magic functions and specially with overloading. Here is an example code:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
class Container
{
private $_data;
 
public function __set($key, $value)
{
$this->_data[$key] = $value;
}
 
public function __get($key)
{
return $this->_data[$key];
}
 
public function __isset($key)
{
return isset($this->_data[$key]);
}
 
public function __unset($key)
{
if ($this->__isset($this->_data[$key]))
unset($this->_data[$key]);
}
}

when you try to use this code with arrays for example:

1
2
3
4
$c = new Container;
$c->arr = array();
$c->arr['test'] = 'test';
var_dump($c->arr['test']);

it rise a notice: Indirect modification of overloaded property Container::$arr has no effect.
and $c1->arr['test'] is null instead of test.

a work around is first to get this array into a temporary variable, make changes you need and then set it again.

1
2
3
4
5
6
$c = new Container;
$c->arr = array();
$tmpArr = $c->arr;
$tmpArr['test'] = 'test';
$c->arr = $tmpArr;
var_dump($c->arr['test']);

this one works as expected. Actually php interpreter seems to do same thing. Trying to get value if exists and change it. Problem is that when it takes this value there is no place to store it and rise this error. Trying to modify property in not existing array. Solution is to make this array available. Returning values by reference seems to work.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
class Container
{
private $_data;
 
public function __set($key, $value)
{
$this->_data[$key] = $value;
}
 
public function &__get($key)
{
return $this->_data[$key];
}
 
public function __isset($key)
{
return isset($this->_data[$key]);
}
 
public function __unset($key)
{
if ($this->__isset($this->_data[$key]))
unset($this->_data[$key]);
}
}

Now this code works as expected:

1
2
3
4
$c = new Container;
$c->arr = array();
$c->arr['test'] = 'test';
var_dump($c->arr['test']);

Share/Save/Bookmark

One Response to “php magic __set and __get”

  1. ???Blog » Blog Archive » PHP5??????: Indirect modification of overloaded property has no effect Says:

    [...] php magic __set and __get this one works as expected. Actually php interpreter seems to do same thing. Trying to get value if exists and change it. Problem is that when it takes this value there is no place to store it and rise this error. Trying to modify property in not existing array. Solution is to make this array available. Returning values by reference seems to work. [...]

Leave a Reply