2016-01-19 101 views
1

以下的Yii2 Screencastsyii2財產來源不明

我已經創建了GII控制器GreetingController如下的例子(第2視頻):

<?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)); 
    } 

} 

並查看該代碼:

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

我在這裏嘗試的是從控制器類訪問變量。我正在上線財產來源不明錯誤:

echo $this->message2; 

如果我刪除了這條線,這將成功地顯示在$內容變量的值。因爲在上面提到的視圖教程中,我們有兩種方法可以將數據從控制器傳遞到視圖,如果我們在數組中傳遞變量,則第一種方法工作正常。但是當我試圖直接從視圖訪問公共變量時,我得到這個錯誤。任何人都可以建議我做錯了什麼?

+0

哪些呢的var_dump($這個)輸出? – bpoiss

+0

它輸出一個巨大的文本,跨越整個頁面或兩個頁面。 –

+0

請http://pastebin.com/它 – bpoiss

回答

1

如果你想直接訪問公共變量,你必須使用你的對象上下文變量。

$this->context->yourVariable 

所以你的情況:

$this->context->message2 
+1

謝謝@bpoiss,幫助我擺脫這個問題:) –

+0

沒問題,我很高興我可以幫助:) – bpoiss

+0

是的我同意,這不是最好的做法。但我只想遵循可用的2種方法將數據從控制器傳遞到視圖。只是試圖確保我可以使用兩種方式:) –