PHP Accessor Functions and Arrays

Using the __set accessor function in PHP, I can set the scalar value, but not the array element. I.e:

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

My assistant looks like this:

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

Thanks!

+4
source share
1 answer
 $p->myarray['title'] = "Hello"; 

This does not invoke the __set magic method; you definitely do not set the property, you change part of it. In this case, PHP will call the __get method to retrieve the array stored in the $p->myarray , if such a magic method exists. Please note that to change the return value to any effect on the property, you need to return by the link:

 function &__get($mbr_name) { return $this->$mbr_name; } 
+9
source

Source: https://habr.com/ru/post/1313286/


All Articles