tags:

views:

34

answers:

1

Using a __set accessor function in PHP I can set the value of a scalar, but not an element of an array. Ie:

$p->scalavar = "Hello";  // This works fine
$p->myarray['title'] = "Hello";  //This does not work

My accessor is as follows:

function __set($mbr_name, $mbr_value) {
    $this->$mbr_name = $mbr_value;
}

Thanks!

+7  A: 
$p->myarray['title'] = "Hello"; 

This doesn't call the __set magic method; you're not exactly setting the property, you're changing a part of it. In this case, PHP will call the __get method to retrieve the array stored in the property $p->myarray if such magic method exists. Note that for the change to the returned value to have any effect on the property, you have to return by reference:

function &__get($mbr_name) {
    return $this->$mbr_name;
}
Artefacto