Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP Accessor functions and arrays

Tags:

php

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!

like image 644
DatsunBing Avatar asked Jun 03 '26 10:06

DatsunBing


1 Answers

$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;
}
like image 103
Artefacto Avatar answered Jun 06 '26 05:06

Artefacto



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!