Using setters/getters with array of objects

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

 



Hi,

I have two classes User and Email where one User can have many Emails so
I've done like this

class Email
{
    protected $_email;

    public function __get($name)
    {
        $property = '_' . $name;
        return $this->$property;
    }

    public function __set($name, $value)
    {
        $property = '_' . $name;
        $this->$property = $value;
    }
}


class User
{
    protected $_name;
    protected $_emails = array();

    public function __get($name)
    {
        $property = '_' . $name;
        return $this->$property;
    }

    public function __set($name, $value)
    {
        $property = '_' . $name;
        $this->$property = $value;
    }

}

So I'd like to

$u = new User();
$u->name = 'xxxx';

$e = new Email();
$e->email = 'xxx@xxxxxxxx';

$u->emails[] = $e;

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;
        }
    }

And then

$u = new User();
$u->name = 'xxxx';

$e = new Email();
$e->email = 'xxx@xxxxxxxx';

$u->emails = $e;

But this can confuse the programmer.  Any ideas of why it is not working?

[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