Difference Between setData() and addData()

setData overrides the existing data and can receive as parameter either a pair key-value either an array.
if you set as parameters a pair key-value then $_data[key] becomes value. If you set as parameter an array $_data becomes that array overwriting what ever it contained previously.
Example:

$_data = array('k1' => 'v1' , 'k2' => 'v2');

calling $obj->setData('k3','v3') results in

$_data = array('k1' => 'v1' , 'k2' => 'v2', 'k3'=>'v3');

calling $obj->setData(array('k3'=>'v3')) results in

$_data = array('k3'=>'v3');

calling $obj->setData('k2','v2000') results in

$_data = array('k1' => 'v1' , 'k2' => 'v2000')

calling $obj->setData(array('k2'=>'v2000')) results in

$_data = array('k2'=>'v2000');

addData receives as parameter only an array and it merges that array with the existing data.

Example:

$_data = array('k1' => 'v1' , 'k2' => 'v2');

calling $obj->addData(array('k3'=>'v3')) results in

$_data = array('k1' => 'v1' , 'k2' => 'v2', 'k3'=>'v3');

but calling $obj->addData(array('k2'=>'v2000')) results in

$_data = array('k1' => 'v1' , 'k2' => 'v2000');

setData()

function is only set one field value on one call. it can set multiple field value using multiple call of setData function.

addData() function is set multiple field values using array with array key as field index.

Just Example:

You want two field to set at object.

  • field a>Value->X
  • field b>Value->Y

If i using setData() then you need to do this type of works.need For two field you need call setData function two wise.

$ObVarien->setData('fieldA',$X);
$ObVarien->setData('fieldB',$Y);

But if i using addData() then you can do this array key as field name

$Data=array('fieldA'=>$X,'fieldb'=>$Y)

$ObVarien->addData($Data)

addData() and setData() are two Library Varien_Object class function.

addData() using setData() at lib file for set field value using loop.

public function addData(array $arr)
{
    foreach($arr as $index=>$value) {
        $this->setData($index, $value);
    }
    return $this;
}

Tags:

Collection