Search code examples
phppropertiesyiiyii-components

Constructing a CComponent


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.


Solution

  • 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);
       }
    }