Re: Using setters/getters with array of objects
| From: | Tommy Pham | Date: | Sun, 18 Oct 2009 17:24:04 +0000 |
| Subject: | Re: Using setters/getters with array of objects | ||
| References: | 1 | Groups: | php.general |
| Request: | Send a blank email to php-general+get-299030@lists.php.net to get a copy of this message | ||
----- Original Message ----
> From: mbneto <mbneto@gmail.com>
> To: php-general@lists.php.net
> Sent: Sun, October 18, 2009 8:31:53 AM
> Subject: [PHP] Using setters/getters with array of objects
>
> 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
Of course it doesn't work because you didn't have 'set' method for the protected
$_emails.
http://www.php.net/manual/en/language.oop5.visibility.php
>
> 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?
I suggest you don't use magic methods as it's too ambiguous and hard to expand your code
later. Your 2 classes could be summarized as 1 class below:
class User
{
protected $_name;
protected $_emails = array();
public function getName()
{
return $this->_name;
}
public function setName($value)
{
$this->_name = $value;
}
public function getEmails() {
return $this->_emails();
}
public function setEmails($arrayList) {
$this->_emails = $arrayList;
}
public function setEmail($name, $value) {
$this->_emails[$name] = $value;
}
public fuction getEmail($name) {
if (isset($this->_emails[$name]))
return $this->_emails[$name];
else
return null;
}
}
$u = new User();
$u->setName('jon doe');
$u->setEmail('email1', 'jon@inter.net');
Regards,
Tommy