1、模板引擎 Template.php
<?php
namespace _0809test;
/*
* 模板引擎:
* 1. 存储一组变量
* 2. 读取模板文件: 扩展名任意, 但内容都是php+html
* 3. 将变量与模板文件组装输出一个动态页面
*/
class Template
{
// 变量容器:关联数组
private $data=[];
//模板文件
private $file;
//构造方法:获取到模板文件名称
public function __construct($file)
{
$this->file=$file;
}
// 模板赋值
public function set($name,$value)
{
$this->data[$name]=$value;
}
// 生成模板输出
public function display()
{
// 提取模板变量: extract(): 将关联数据转为独立的变量名值对
extract($this->data);
// 开启缓冲区, 只生成数据并不输出到页面中
ob_start();
// 加载模板文件
include $this->file;
// 返回缓冲区内容
$string=ob_get_contents();
// 并关闭缓冲
ob_end_clean();
// 返回模板文件
return $string;
}
}点击 "运行实例" 按钮查看在线实例
2、模板文件 hello.tmp.php
<!doctype html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>模板文件</title> </head> <body> <?php echo $name; ?> <hr> <?php echo $sex; ?> </body> </html>
点击 "运行实例" 按钮查看在线实例
3、 加载 模板引擎 实例化 index.php
<?php
namespace _0809test;
// 加载 模板引擎
require 'Template.php';
// 实例化模板引擎
$template=new Template('hello.tmp.php');
// 模板赋值
$template->set('name','admin');
$template->set('sex','女');
// 输出模板
echo $template->display();点击 "运行实例" 按钮查看在线实例
运行结果:

Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号