首页 > php教程 > PHP源码 > 正文

先识别标签后计算的模板思路

PHP中文网
发布: 2016-05-25 17:13:23
原创
1005 人浏览过

传统模板引擎的思路是:计算模板变量->设置模板变量(assign)->整合模板并显示页面。
现在想要实现这样的效果:识别模板变量->计算模板变量->整合并显示页面。
这里提供一种思路,利用PHP的魔术方法 __call 来实现。

<?php
//模板变量处理对象:
class template
{
public function main($op)
{
return $this;
}

public function __call($name,$args)
{
$method_name = &#39;get_&#39;.$name;

if (!method_exists($this, $method_name))
{
cwarning(&#39;找不到模板变量:&#39;,$name);
}

if (!empty($args))
{
$r = $this->$method_name($args[0]);
}
else
{
$r = $this->$method_name();
}

return $r;
}

/**
 * hello world
 * @return string
*/
public function get_test($op)
{
return &#39;hello world!&#39;;
}
}
登录后复制
<html>
<body>
<?php
//获得模板变量对象
$o = new template();
$tpl = $o->main();

//声明页面标签
$test = $tpl->test();
?>

<div><?php echo $test; ?></div>
</body>
</html>
登录后复制
来源:php.cn
本站声明
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
热门推荐
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责声明 Sitemap
PHP中文网:公益在线PHP培训,帮助PHP学习者快速成长!