【问题标题】:assigning variables to MVC view class?将变量分配给 MVC 视图类?
【发布时间】:2013-01-01 17:26:15
【问题描述】:

我正在用 MVC 基本概念构建一个简单的 php MVC

在构建视图类时,我尝试构建一个简单的函数,让我将变量从控制器传递到视图

<?php

class View {
    protected $data = array();

    function __construct() {
        //echo 'this is the view';
    }
    public function assign($variable , $value)
    {
        $this->data[$variable] = $value;
    }

    public function render($name, $noInclude = false)
    {
        extract($this->data);
        if ($noInclude == true) {
            require 'views/' . $name . '.php';    
        }
        else {
            require 'views/header.php';
            require 'views/' . $name . '.php';
            require 'views/footer.php';    
        }
    }


}

在我的控制器类中我曾经这样使用

class Index extends Controller {

    function __construct() {
        parent::__construct();
    }

    function index() {
        $this->view->assign('title','welcome here codes');
        $this->view->render('index/index',true);
    }

渲染函数工作正常,但分配函数有问题,因为当我试图从视图中打印出变量时,它什么也没显示

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Test Code</title>
</head>
<body>
<? echo $title;?> 
some text here
</body>
</html>

我尝试将 View 类中的受保护变量更改为 public,但它没有影响问题,我仍然无法从控制器中打印出任何变量

【问题讨论】:

    标签: php templates variable-assignment


    【解决方案1】:

    它什么也不显示,因为您需要 View::render 函数中的视图,因此要访问您的数据,您应该编写

    <?php echo $this->data['title']; ?>
    

    为避免这种情况,您应该在渲染函数中从数据数组创建变量。我的意思是像

    foreach($this->data as $key => $value) {
      $$key = $value;
    }
    

    注意:由于变量作用域,上面的代码不能存在于您的“提取”函数中。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-05-11
      • 2012-05-07
      相关资源
      最近更新 更多