Jump to content

__set arrays


nicholasstephan

Recommended Posts

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.

Link to comment
https://forums.phpfreaks.com/topic/210848-__set-arrays/
Share on other sites

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

Link to comment
https://forums.phpfreaks.com/topic/210848-__set-arrays/#findComment-1099797
Share on other sites

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.