Re: Using setters/getters with array of objects
| From: | mbneto | Date: | Tue, 20 Oct 2009 19:22:09 +0000 |
| Subject: | Re: Using setters/getters with array of objects | ||
| References: | 1 2 | Groups: | php.general |
| Request: | Send a blank email to php-general+get-299131@lists.php.net to get a copy of this message | ||
Hi,
Thanks. I'll probably do the addEmail method. I was hoping to do as with
the other "non-array" properties.
On Sun, Oct 18, 2009 at 1:00 PM, Andy Shellam (Mailing Lists)
<andy-lists@networkmail.eu> wrote:
> 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)
> {
> $property = '_' . $name;
>
> switch($name)
> {
> case 'emails':
> array_push($this->$property, $value);
> break;
>
> default:
> $this->$property = $value;
> }
> }
>
>
> You could also have done:
>
> if (is_array($this->$property))
> {
> 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.)
>
>