Setters done right

In case you're a fan of addding setters to your class or DataExtension avoid some simple pitfalls.

You can write a setter for several reasons. One might be you're used to it and find it a good practise. Others might be you need an alias, e.g.

public function setOrganisation($val)
{
    $this->Company = $val;
}

which is ok.

But if you just want a setter method to save the a DB field with the same name this might not work:

public function setCompany($val)
{
    $this->Company = $val;
}

Why? Well, the variable $this->Company is not defined by default, so it'll call the magic ViewableData::__set() method, which checks if there is a setter for this variable... Which is your setter.

If there is no setter, __set() will just call $this->setField(), which saves the value to the right place.

So the above example would work like this:

public function setCompany($val)
{
    $this->setField('Company', $val);
}

 

Rate this post

Post your comment

Comments

No one has commented on this page yet.

RSS feed for comments on this page | RSS feed for all comments