MyTpl.class.php
1 <?php
2 class MyTpl
3 {
4 private $tpl_vars = array();
5 //分配
6 public function assign($key,$value){
7 $this->tpl_vars[$key] = $value;
8 }
9 public function display($tpl){
10 $contents = file_get_contents($tpl);
11 foreach ($this->tpl_vars as $k => $v){
12 //替換 將{$name} 替換成真實的數據
13 $contents = str_replace('{$'."$k".'}',"$v", $contents);
14 $compile = './templates_c/'.md5('show.html') . '.php';
15 file_put_contents($compile, $contents);
16 require $compile;
17 }
18 }
19 }
20 $tpl = new MyTpl;
21 $tpl-> assign('name','張四');
22 $tpl-> display('./template/show.html');
template/show.html
1 <!DOCTYPE html>
2 <html>
3 <head>
4 <meta charset="UTF-8">
5 <title>Insert title here</title>
6 </head>
7 <body>
8 {$name}
9 </body>
10 </html>