我想在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!!
的問題是我在頂級視圖設置的變量沒有得到傳遞給內嵌視圖。我怎麼能做到這一點?
謝謝。這讓我意識到,即使在大型框架中,您也應該在控制器中渲染視圖,然後將變量中的渲染視圖傳遞到頂層視圖。我試圖在另一個視圖內渲染視圖。 – ryeguy 2009-07-21 18:36:34