$this->field1='x' vs. $this->setAttribute(...)

I have seen in various threads the use of:


public function beforeSave()

{

   if(parent::beforeSave()) {

      $this->field='something';

   }

}

and this:


public function beforeSave()

{

   if(parent::beforeSave()) {

      $this->setAttribute('field', 'something');

   }

}



[size="1"]NOTE: setAttribute() syntax may not be exactly right.[/size]

What’s the difference? Which is better? IS one any better than the other?

Thanks.

There’s no “better” in this case - it depends. Both do practically the same, but setAttributes() is a fraction faster.

Check out the source code of CActiveRecord::__set(), it will be used in your first case.

Thanks. Is there a "case" where setAttribute() is better, or vica versa?

As Mike said - you can see if you look at the code for CActiveRecord.

$this->setAttribute(‘field’, ‘value’) will always be very slightly faster than $this->field = ‘value’ because the ‘field’ attribute doesn’t actually exist as such in the class, so doing $this->field = ‘value’ actually calls the PHP magic setter method __set($field, $value), which is defined in CActiveRecord to run the setAttribute() method. So basically, $this->field = ‘value’ is a wrapper for $this->setAttribute(‘field’, ‘value’).

So, if you want to make a very tiny gain in speed, then use setAttribute(), but if you want perhaps to gain in readability then just use $this->field = ‘value’.