Michael
Michael

Reputation: 2187

pass variables from controller to view in Yii

I cannot use the variables specified in controller in the corresponding view. Here is my code:

public function actionHelloWorld()
    {

        $this->render('helloWorld',array('var'=>'this is me'));
    }

In the helloWorld.php (view file):

<h1>Hello, World!</h1>
<h3><?php echo $var; ?></h3>

It only prints out "Hello, World!", looks like $var is unaccessible in the view. Anyone?

Upvotes: 6

Views: 16546

Answers (2)

Neil McGuigan
Neil McGuigan

Reputation: 48287

that should work, though with any variable name other than 'var'

please note that 'this' in a view refers to its controller, so if you have a public member variable or method in a controller, you can access it from the view:

MyController.php:

class MyController extends CController{
  public $foo = 'bar';

  public function actionIndex(){
    $this->render('index');
  }
}

index.php:

<?php 

echo $this->foo; //result is bar

?>

Upvotes: 4

ryanlahue
ryanlahue

Reputation: 1151

"var" is a reserved word in PHP, so you won't be able to use that name for your variable. See: http://www.php.net/manual/en/reserved.keywords.php

Try using a different variable name and it should work.

Upvotes: 5

Related Questions