将公共的代码封装到Smarty的compile()方法中
<?php
class Smarty{
private $tpl_var = array();
public function assign($k, $v){
$this->tpl_var[$k] = $v;
}
public function compile(){
//取出demo.html文档中的内容
$str = file_get_contents('./demo.html');
//替换定界符的代码,在oop中取值的方法,注意面向过程不同
$str = str_replace('{', '<?php echo $this->tpl_var["', $str);
$str = str_replace('}', '"]; ?>', $str);
//将这个文件写入demo.html.php,demo.html.php为混编文件
file_put_contents('./demo.html.php', $str);
require './demo.html.php';
}
}
使用代码demo.php:
<?php
require './Smarty.class.php';
$smarty = new Smarty();
$smarty->assign('title', '锄禾');
$smarty->assign('content', '锄禾日当午,汗滴禾下土。谁知盘中餐,粒粒皆辛苦。');
$smarty->compile();
demo.html:
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="Generator" content="EditPlus®">
<meta name="Author" content="">
<meta name="Keywords" content="">
<meta name="Description" content="">
<title>Document</title>
</head>
<body>
{title} <br/>
{content}
</body>
</html>