【发布时间】:2010-11-12 17:53:06
【问题描述】:
我正在尝试用 PHP 构建一个骨架视图系统,但我不知道如何让嵌入式视图接收其父级的变量。例如:
查看类
class View
{
private $_vars=array();
private $_file;
public function __construct($file)
{
$this->_file='views/'.$file.'.php';
}
public function set($var, $value=null)
{
if (is_array($var))
{
$this->_vars=array_merge($var, $this->_vars);
}
else
$this->_vars[$var]=$value;
return $this;
}
public function output()
{
if (count($this->_vars))
extract($this->_vars, EXTR_REFS);
require($this->_file);
exit;
}
public static function factory($file)
{
return new self($file);
}
}
test.php(顶层视图)
<html>
<body>
Hey <?=$name?>! This is <?=$adj?>!
<?=View::factory('embed')->output()?>
</body>
</html>
embed.php(嵌入在test.php中
<html>
<body>
Hey <?=$name?>! This is an embedded view file!!
</body>
</html>
代码:
$vars=array(
'name' => 'ryan',
'adj' => 'cool'
);
View::factory('test')->set($vars)->output();
输出:
Hey ryan! This is cool! Hey [error for $name not being defined]
this is an embedded view file!!
问题是我在顶层视图中设置的变量没有传递给嵌入式视图。我怎样才能做到这一点?
【问题讨论】: