how to initialize custom properties in Model class

Hello all,

I’m facing a difficulty regarding initializing a custom property of a model class.

I have a Group model class that has a relation with Subgroup class one to many. Subgroup has a relation one to many with Member model class.

I declared this relationship in Group model:

'subgroups'=>array(self::HAS_MANY, 'Subgroup', 'Subgroup_id'),


Now what I want is the total of members for a Group as a property of Group, so I added a public property in the class but don’t know where to initialize it.

public $totalMembers;

I would like to access this value as a property in the following fashion:


instead of


I tried to override the init() method of my active record, but apparently when it is called I still don’t have an instance of Group and the code fails.

I guess there should be a way to do it and maybe the question is too simple but I honestly don’t know how to do it. Can anybody point me into the right direction here?

If your model has a method getWhatever() you’ll be able to access it from outside of the model with $model->whatever, just like a property. That is because of the Yii’s implementation of __get() magic method.

So you don’t have to declare the property, all you have to do is to have a method starting with “get”.

Excellent, thank you very much!