yii2 未知 属性
yii2 Unknown Property
中的示例(第二个视频)
我用 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>
我在这里尝试的是从控制器 class 访问变量。我收到未知 属性 在线错误:
echo $this->message2;
如果我删除这一行,它将成功显示 $content 变量的值。因为在我上面提到的视图教程中,有两种方法可以将数据从控制器传递到视图,如果我们传递数组中的变量,第一种方法工作正常。但是,当我尝试直接从视图访问 public 变量时,出现此错误。谁能指出我做错了什么?
如果您想直接访问 public 变量,则必须使用您的对象上下文变量。
$this->context->yourVariable
所以在你的情况下:
$this->context->message2
我用 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>
我在这里尝试的是从控制器 class 访问变量。我收到未知 属性 在线错误:
echo $this->message2;
如果我删除这一行,它将成功显示 $content 变量的值。因为在我上面提到的视图教程中,有两种方法可以将数据从控制器传递到视图,如果我们传递数组中的变量,第一种方法工作正常。但是,当我尝试直接从视图访问 public 变量时,出现此错误。谁能指出我做错了什么?
如果您想直接访问 public 变量,则必须使用您的对象上下文变量。
$this->context->yourVariable
所以在你的情况下:
$this->context->message2