CJSON::encode() seems to bypass __get() override


I’m fairly new to Yii. I have a model class that overrides the __get() magic method to modify the value of an attribute retrieved from the database before it is returned by the class. This seems to work as expected. However, when I return the AR model as a JSON string the value of the attribute is not modified as expected. For example, the __get() override in the model class looks something like this:

class CustomContent extends CActiveRecord


public function __get($name)


if ($name == 'released')


  // Always return the value of 'released' in lowercase.

  return strtolower(parent::__get($name));

}// if

return parent::__get($name);



If, in the controller, I have code like this:

$ccAR = CustomContent::model()->find($criteria);

$rel = $ccAR->released;

The value of $rel is always lowercase, as expected.

But if I do the following:

echo CJSON::encode($ccAR);

The value of ‘released’ in the JSON string is as it came from the database - not always in lowercase. The __get() function is bypassed and never called.

Is this how this should work? I can get it to kinda work in the controller by the following code, but it should be in the model so the it is hidden from the controller.

$ccAR->released = $ccAR->released;

echo CJSON::encode($ccAR);

or I can add a function to the model class like:

public function jsonEncode()


$arr = $this->getAttributes();

foreach ($arr as $key => $value)


  $arr[$key] = $this[$key];

}// foreach

return json_encode($arr);


Then, in the controller call this function instead of CJSON::encode() like:

echo $customContentAR->jsonEncode();

What is the better solution?


Hi and welcome to the forums!

Did you look at afterFind()? It is called after your record is populated with data from DB. You can do any conversion you want there. This is more safe than what you try above. You should only override PHP’s magic methods if there’s really no other (efficient) way to solve something.

Oh and BTW.: I did not read your complete code, mainly because it’s hard to read. You could use the <> button in the topic editor to make some selected text become a code example. Much easier to read. (You can also edit your message afterwards - try it! ;) )

Thanks for the information and advice. Its much appreciated.