Why Does Yii Allow Me To Access The Private $This->_Property, With $This->Property?

I’m not sure what’s happening here, perhaps someone has a clue:

On my layout I have this:

<div id="main-content" class="<?= $this->getMainClass(); ?>">

On components>controller class I have this:

 private $_mainCssClass;

    public function setMainCssClass($className) {

     if (is_string($className)) {

        $this->_mainCssClass = $className;

     } else {




    public function getMainCssClass() {

     return $this->_mainClass;


What I’m not getting is, despite the fact that we are using accessors, and the mainCssClass property has an underscore and it’s declared private, I can access it trough:


The same as: $this->getMainCssClass()


There is no problem.

You do not access this->_mainClass, you access getMainCssClass() (which is public, ok). Then getMainCssClass() access the private property. getMainCssClass() is a method of the class, so it can access the private variable.


you will learn a lot with this article: http://phpmaster.com/yii-under-the-hood-1/

It explains the inner workings of Yii components. :)