【问题标题】:yii2 Unknown Propertyyii2 未知属性
【发布时间】: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) 输出什么?
  • 它输出大量文本,跨越一两个页面。
  • pastebin.com
  • 试试$this-&gt;context-&gt;message2
  • 在这个例子中,变量也是通过 render 方法传递的,我建议你总是使用这个方法将变量传递给你的视图,不要直接访问它们。请参阅en.wikipedia.org/wiki/Encapsulation_(computer_programming),了解为什么这是最佳做法的详细信息。

标签: php windows xampp yii2 yii2-basic-app


【解决方案1】:

如果你想直接访问公共变量,你必须使用你的对象上下文变量。

$this->context->yourVariable

所以在你的情况下:

$this->context->message2

【讨论】:

  • 感谢@bpoiss,帮我解决了这个问题:)
  • 没问题,很高兴能帮上忙 :)
  • 是的,我同意,这不是最佳做法。但我只想遵循可用的两种方法将数据从控制器传递到视图。只是想确保我可以同时使用这两种方式:)
猜你喜欢
  • 2014-06-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-07-13
  • 2018-09-12
  • 2015-04-30
  • 2023-01-04
  • 1970-01-01
相关资源
最近更新 更多