Why Is Magic __Get() Method Not Working Here?


    private function getRandomQuote()

    {

        return $this->_quotes[array_rand($this->_quotes, 1)];

    }


	public function actionIndex()

	{

		$this->render('index', array(

            'quote'=>$this->randomQuote

        ));

	}


    public function actionGetQuote()

    {

        $this->renderPartial('_quote', array(

            'quote'=>$this->randomQuote

        ));

    }

this code generates an error:

Why am I not able to do this in this code? The only way to get it to work would be to change randomQuote to ‘quote’=>$this->getRandomQuote()

it’s because you declared it as private, it should be protected or public

Thanks.

I don’t understand why though. Private allows access only within the current class, in this case it’s QuoteController. By making it protected I allow Controller to use it as well, but why would it need to? I’m a little lost.

It’s because __get() method declared in CComponent so your method will not be called in private scope. anyway in my opinion it’s better to avoid using this approach when it’s not necessary, why don’t call the method directly when we can?

Got it, thanks for taking the time to explain.