Initializing Some Variables Before Calling An Action

Hi,

My testReportController looks like-

[indent]<?php

class TestReportController extends Controller

{

    [indent]&#036;url = &quot;&lt;some url&gt;&quot;;


public function init()


{


	[indent]&#036;url = &quot;&lt;some url&gt;&quot;;[/indent]	


}


    function actionSup()


{


            [indent]//&#036;url = &quot;&lt;some url&gt;&quot;;


	Yii::log(&#036;url.'sup','info','info');[/indent]


}


    // plus some other action methods

[/indent]

}

?>

[/indent]

When I un comment the line initializing url from actionSup it works. But when I try to put it in log with either the first $url or the second it says "Undefined variable : url "

I want to initialize a variable url before doing any ‘action’. I have tried using the above controller but it doesn’t put anything in the log. What is wrong. I don’t want to create any object of this controller class eventually calling the constructor, but I want to avoid the repetition of putting url variable in every action, instead I want a global url variable initialize only when I do some action.

Please help. I have been trying this for a while.

It’s normal that you’re getting such error, because accessing to the objects’ properties in PHP is made by $this keyword.

So, your code would look like:




<?php

class TestReportController extends Controller

{

	$url = "<some url>";

	public function init()

	{

		$this->url = "<some url>";

	}

	function actionSup()

	{

		//$url = "<some url>";

		Yii::log($this->url.'sup','info','info');


	}

	// plus some other action methods


}

?>



Learn more about OOP and PHP: http://www.php.net/manual/en/language.oop5.basic.php

It gives an error saying - "exception ‘CException’ with message 'Property “TestReportController.url” is

not defined".

I think you forgot to make the first url variable public / private. When I change the first line from the controller to

[indent]public $url = "<some url>";[/indent]

it works.

Yes, you’re right. I’ve accidently forgot about it. :)

You’re welcome.