pass variables from controller to view in Yii

yii
16,484

Solution 1

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

Solution 2

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

?>
Share:
16,484
Michael
Author by

Michael

newbie in web programming

Updated on June 21, 2022

Comments

  • Michael
    Michael almost 2 years

    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?