Using setters/getters with array of objects

From: Date: Sun, 18 Oct 2009 15:31:53 +0000
Subject: Using setters/getters with array of objects
Groups: php.general 
Request: Send a blank email to php-general+get-299028@lists.php.net to get a copy of this message
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@xxxx.com'; $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@xxxx.com'; $u->emails = $e; But this can confuse the programmer. Any ideas of why it is not working?

« previous php.general (#299028) next »