Yii2 virtual attribute getter had to change to function call

810 Views Asked by At

I'm new to OOP and Yii2. I have a function in Model:

public function getDatRev() {
    if ($this->rev) {
        return $this->rev;
    } else {
        return $this->datum;
    }
}

in the View until now I have used it like this:

$model->datRev;

and it would return the correct value. Now I don't know what has changed, maybe I was also updated the framework, but the old construct doesn't work anymore, and in order to make it work I have to change it to:

$model->getDatRev();

Can you please explain to me why that is?

2

There are 2 best solutions below

0
Timur On

When you try get property the Yii2 calls magic method __get (). Return value is depend from implementation of this method in parent class. Yii2 can check if this property exist in some container, or if exist getter of this property. In your case seems like you don't call parent's method __get(). This may have happened because you override __get() method or initialized this property.

1
Bizley On

Your class needs to extend yii\base\Object (directly or not) in order to use short property syntax ($model->abc instead of $model->getAbc()). Magic method __get() @Timur mentioned is defined there and further extended in yii\base\Component class.