Yii Framework Forum: Why Is Magic __Get() Method Not Working Here? - Yii Framework Forum

Jump to content

Page 1 of 1
  • You cannot start a new topic
  • You cannot reply to this topic

Why Is Magic __Get() Method Not Working Here? Rate Topic: -----

#1 User is offline   haosmark 

  • Junior Member
  • Pip
  • Yii
  • Group: Members
  • Posts: 35
  • Joined: 27-January 13

Posted 20 February 2013 - 10:25 AM

    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:

Quote

QuoteController and its behaviors do not have a method or closure named "getrandomQuote".


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()
0

#2 User is offline   Reza m 

  • Standard Member
  • PipPip
  • Yii
  • Group: Members
  • Posts: 148
  • Joined: 07-March 12

Posted 20 February 2013 - 11:27 AM

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

#3 User is offline   haosmark 

  • Junior Member
  • Pip
  • Yii
  • Group: Members
  • Posts: 35
  • Joined: 27-January 13

Posted 20 February 2013 - 12:08 PM

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.
0

#4 User is offline   Reza m 

  • Standard Member
  • PipPip
  • Yii
  • Group: Members
  • Posts: 148
  • Joined: 07-March 12

Posted 20 February 2013 - 01:20 PM

View Posthaosmark, on 20 February 2013 - 12:08 PM, said:

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?
0

#5 User is offline   haosmark 

  • Junior Member
  • Pip
  • Yii
  • Group: Members
  • Posts: 35
  • Joined: 27-January 13

Posted 20 February 2013 - 01:54 PM

Got it, thanks for taking the time to explain.
0

Share this topic:


Page 1 of 1
  • You cannot start a new topic
  • You cannot reply to this topic

1 User(s) are reading this topic
0 members, 1 guests, 0 anonymous users