Re: Using setters/getters with array of objects
| From: | Mailing Lists) | Date: | Sun, 18 Oct 2009 17:00:46 +0000 |
| Subject: | Re: Using setters/getters with array of objects | ||
| References: | 1 | Groups: | php.general |
| Request: | Send a blank email to php-general+get-299029@lists.php.net to get a copy of this message | ||
Hi,
$u->emails[] = $e;I would hazard a guess because $u->emails isn't a concrete object (whereas $u->_emails is, but is private.) It's sort of a virtual reference - PHP has no way of knowing that $u->emails actually translates into _emails which is an array, if you see what I mean (it's difficult to explain.)
But that does not work. I've managed to achieve similar result using a different setter in User public function __set($name, $value) {You could also have done: if (is_array($this->$property)) {$property = '_' . $name;switch($name) { case 'emails': array_push($this->$property, $value); break;default: $this->$property = $value; }}
array_push($this->$property, $value);} else {
$this->$property = $value;} which would handle any array property, not just the e-mails property. If this was me, I would probably create a concrete method, called "addEmail" which would do $this->_emails[] = $value, but allow a programmer to call $user->emails to get the e-mails (not set.)