Heim  >  Artikel  >  php教程  >  先识别标签后计算的模板思路

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

PHP中文网
PHP中文网Original
2016-05-25 17:13:23990Durchsuche

传统模板引擎的思路是:计算模板变量->设置模板变量(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>
Stellungnahme:
Der Inhalt dieses Artikels wird freiwillig von Internetnutzern beigesteuert und das Urheberrecht liegt beim ursprünglichen Autor. Diese Website übernimmt keine entsprechende rechtliche Verantwortung. Wenn Sie Inhalte finden, bei denen der Verdacht eines Plagiats oder einer Rechtsverletzung besteht, wenden Sie sich bitte an admin@php.cn