【发布时间】:2013-06-21 04:21:21
【问题描述】:
在几乎所有关于 SO 的教程或答案中,我看到了一种将数据从 Controller 发送到 View 的常用方法,View 类通常看起来与下面的代码类似:
class View
{
protected $_file;
protected $_data = array();
public function __construct($file)
{
$this->_file = $file;
}
public function set($key, $value)
{
$this->_data[$key] = $value;
}
public function get($key)
{
return $this->_data[$key];
}
public function output()
{
if (!file_exists($this->_file))
{
throw new Exception("Template " . $this->_file . " doesn't exist.");
}
extract($this->_data);
ob_start();
include($this->_file);
$output = ob_get_contents();
ob_end_clean();
echo $output;
}
}
我不明白为什么需要将数据放入数组中,然后调用 extract($this->_data)。 为什么不直接将一些属性从控制器像
$this->_view->title = 'hello world';
然后在我的布局或模板文件中我可以这样做:
echo $this->title;
【问题讨论】:
标签: php templates variable-assignment