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
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] stas@php.net

 

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
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.