2

BranchSalaries is a class derived from CComponent. It has get/set methods for month and year properties.

The following code does not work (more specifically, does not initialize year and month properties):

new BranchSalaries(array('id'=>'branch_salaries', 'year'=>$year, 'month'=>$month));

What is the simplest way to make a class which can be initialized passing an array to the constructor?

Correction BranchSalaries is derived not directly from CComponent but from CDataProvider.

Manquer
  • 7,390
  • 8
  • 42
  • 69
porton
  • 5,214
  • 11
  • 47
  • 95

2 Answers2

2
function __construct($arr){
   foreach($arr AS $key=>$value){
       $this->$key = $value;
   }
}

You need a constructor that can process an array.

Edit: If you need to use the setters: (this assumes the setter is like setId() not setid()

function __construct($arr){
   foreach($arr AS $key=>$value){
       $method = "set".ucfirst($key);
       $this->$method($value);
   }
}
Jessica
  • 7,075
  • 28
  • 39
1

To setup class as Yii does, you can use Yii::createComponent(), and then there is no need to create cunstomized constructor. I your case this would be:

Yii::createComponent(array(
    'class' => 'BranchSalaries',
    'id'=>'branch_salaries',
    'year'=>$year,
    'month'=>$month
));

While it does not look user friendly, it can be used for automatic object creation.

class parameter can also be used with path alias:

Yii::createComponent(array(
    'class' => 'ext.someExtension.BranchSalaries',
    'id'=>'branch_salaries',
    'year'=>$year,
    'month'=>$month
));

Also it set class properties from outside class scope, so getters and setters will be automatically used.