Re: Using setters/getters with array of objects

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

 



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.)


[Index of Archives]     [PHP Home]     [Apache Users]     [PHP on Windows]     [Kernel Newbies]     [PHP Install]     [PHP Classes]     [Pear]     [Postgresql]     [Postgresql PHP]     [PHP on Windows]     [PHP Database Programming]     [PHP SOAP]

  Powered by Linux