M_Idrees
M_Idrees

Reputation: 2182

yii2 Unknown Property

following the example(2nd video) at Yii2 Screencasts

I have created a controller GreetingController with Gii as follows:

<?php

namespace app\controllers;

class GreetingController extends \yii\web\Controller
{
    public $message = 'Message variable from Controller';
    public $message2 = 'Message2 variable from Controller2';

    public function actionIndex()
    {
        return $this->render('index',array('content'=>$this->message));
    }

}

And View with this code listing:

<?php
/* @var $this yii\web\View */

use app\controllers;
use yii\web\Controller;

echo $content;
echo $this->message2;
?>
<h1>greeting/index</h1>

<p>
    You may change the content of this page by modifying
    the file <code><?= __FILE__; ?></code>.
</p>

What I am trying here is to access the variables from controller class. I am getting Unknown Property Error on line:

echo $this->message2;

If I removed this line, It will successfully display the value of the $content variable. Because in the view tutorial I mentioned above, there are 2 ways we can pass data from controller to view, first method is working fine if we pass variables in array. But when I try to access a public variable directly from view, I am getting this error. Can anybody suggest what I am doing wrong?

Upvotes: 1

Views: 559

Answers (1)

bpoiss
bpoiss

Reputation: 14023

If you want to access public variables directly, you have to use your objects context variable.

$this->context->yourVariable

So in your case:

$this->context->message2

Upvotes: 1

Related Questions