2013-01-18 90 views
2

我建立一個簡單的PHP MVC與MVC基本概念將變量分配給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類公共內改變受保護的變量,但它並沒有影響這個問題,我仍然無法從控制器打印出任何變量

+0

查看不是模板。 –

回答

1

它說明不了什麼,因爲你需要查看內部視圖渲染::功能,所以訪問您的數據,你應該寫

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

避免這種情況,內部渲染功能,你應該創建一個從數據數組變量。我的意思是這樣

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

注:上面的代碼就無法生存,因爲變量的作用域你的「提取」功能裏。