龙盟编程博客 | 无障碍搜索 | 云盘搜索神器
快速搜索
主页 > web编程 > php编程 >

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

时间:2014-07-22 14:52来源: 作者: 点击:
分享到:
传统模板引擎的思路是:计算模板变量-设置模板变量(assign)-整合模板并显示页面。br / br / 现在想要实现这样的效果:识别模板变量-计算模板变量-整合并显示页面。br / br / 这里提供
传统模板引擎的思路是:计算模板变量->设置模板变量(assign)->整合模板并显示页面。

现在想要实现这样的效果:识别模板变量->计算模板变量->整合并显示页面。

这里提供一种思路,利用PHP的魔术方法 __call 来实现。



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

	public function __call($name,$args)
	{
		$method_name = 'get_'.$name;

		if (!method_exists($this, $method_name))
		{
			c\warning('找不到模板变量:',$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 'hello world!';
	}
}

2. [代码][PHP]代码     跳至 [1] [2] [全屏预览]

<html>
<body>
<?php
//获得模板变量对象
$o = new template();
$tpl = $o->main();

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

<div><?php echo $test; ?></div>
</body>
</html>
精彩图集

赞助商链接