【发布时间】:2016-04-25 09:26:28
【问题描述】:
按照Yii2 Screencasts的示例(第二个视频)
我用 Gii 创建了一个控制器 GreetingController 如下:
<?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;
如果我删除了这一行,它将成功显示 $content 变量的值。因为在我上面提到的视图教程中,有两种方法可以将数据从控制器传递到视图,如果我们在数组中传递变量,第一种方法可以正常工作。但是当我尝试直接从视图访问公共变量时,我收到了这个错误。谁能建议我做错了什么?
【问题讨论】:
-
var_dump($this) 输出什么?
-
它输出大量文本,跨越一两个页面。
-
试试
$this->context->message2 -
在这个例子中,变量也是通过 render 方法传递的,我建议你总是使用这个方法将变量传递给你的视图,不要直接访问它们。请参阅en.wikipedia.org/wiki/Encapsulation_(computer_programming),了解为什么这是最佳做法的详细信息。
标签: php windows xampp yii2 yii2-basic-app