## 2.6 視圖類
~~~
1. 在控制器方法中使用視圖方法
2. 編寫核心文件2個視圖的方法
3. 創建視圖文件
4. 傳遞數據
~~~
### 1. 在控制器方法中使用視圖方法
* * * * *
*D:\wamp\www\web.com\app\ctrl\indexCtrl.php*
~~~
<?php
namespace app\ctrl;
class indexCtrl extends \core\thinkphp
{
public function index()
{
$data = "Hello World!";
$this->assign('title', $data);
$this->display('index/index.html');
}
}
~~~
備注:`class indexCtrl extends \core\thinkphp` 我們讓index控制器繼承框架核心文件,在核心文件中創建2個視圖的方法
### 2. 編寫核心文件2個視圖的方法
* * * * *
*D:\wamp\www\web.com\core\thinkphp.php*
~~~
public $assign;
......
// 傳遞數據
public function assign($name, $value)
{
$this->assign[$name] = $value;
}
// 顯示視圖
public function display($file)
{
$file = APP.'/view/'.$file;
if (is_file($file)) {
p($this->assign);
extract($this->assign);
include $file;
}
}
~~~
備注:[extract()](http://php.net/manual/zh/function.extract.php) 從數組中將變量導入到當前的符號表
### 3. 創建視圖文件
*D:\wamp\www\web.com\app\view\index\index.html*
~~~
<h1>這是標題</h1>
<h3>段落內容段落內容段落內容段落內容段落內容</h3>
~~~
### 4. 傳遞數據
*D:\wamp\www\web.com\app\ctrl\indexCtrl.php*
~~~
<?php
namespace app\ctrl;
class indexCtrl extends \core\thinkphp
{
public function index()
{
$data = "Hello World!";
$content = "這是一段內容!!!!!!!!!!!!!!!!!!!";
$this->assign('title', $data);
$this->assign('content', $content);
$this->display('index/index.html');
}
}
~~~
在視圖中顯示數據:`D:\wamp\www\web.com\app\view\index\index.html`
~~~
<h1><?php echo $title; ?></h1>
<h3><?php echo $content; ?></h3>
~~~
**顯示效果:**
