nicholasstephan Posted August 16, 2010 Share Posted August 16, 2010 very simple getter/setter in a class: class Foo { private $vars; public function __set($key, $val) { $this->vars[$key] = $val ; } public function __get($key) { return $this->vars[$key]; } } but $bar = new Foo(); $bar->poetry = array(); $bar->poetry[] = "mary had a little lamb"; $bar->poetry[] = "fleece as white as snow"; print_r($bar->poetry); // Array ( ) It kind of makes sense that the $bar->poetry[] = ... assignments aren't hitting the setter, so $vars is never updated beyond $bar->poetry = array(), and you can always $poetry = array("mary had a little lamb", "fleece as white as snow"); $bar->poetry = $poetry; but it's still kind of annoying. Is there any way of setting it up so you can work with arrays in Foo directly? Thanks. Quote Link to comment https://forums.phpfreaks.com/topic/210848-__set-arrays/ Share on other sites More sharing options...
nicholasstephan Posted August 16, 2010 Author Share Posted August 16, 2010 ok - a little more digging and I found bug report #24608, and the php dev teams response: [2004-01-05 05:53 UTC] [email protected] OK, this code actually cannot work (since __set cannot receive the right data to set style['temp'] - it gets only property name, and style['temp'] is not a name). However, you certailnly can make array beforenahd and then assign it to $test->style and it will go through the accessor. I have fixed it to give an error in this case and not to do things which it is not supposed to do. so it is behaving as it should, just not very intuitively... anybody know a workaround to get to work like you'd think it would? cheers Quote Link to comment https://forums.phpfreaks.com/topic/210848-__set-arrays/#findComment-1099797 Share on other sites More sharing options...
trq Posted August 16, 2010 Share Posted August 16, 2010 I'm not sure there is a way of doing this cleanly. I wouldn't be using the magic __set or __get methods if possible. Quote Link to comment https://forums.phpfreaks.com/topic/210848-__set-arrays/#findComment-1099799 Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.