3

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!

1 Answer 1

8
$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;
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.