传统模板引擎的思路是:计算模板变量->设置模板变量(assign)->整合模板并显示页面。
现在想要实现这样的效果:识别模板变量->计算模板变量->整合并显示页面。
这里提供一种思路,利用PHP的魔术方法 __call 来实现。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 | <?php
class template
{
public function main( $op )
{
return $this ;
}
public function __call( $name , $args )
{
$method_name = 'get_'. $name ;
if (!method_exists( $this , $method_name ))
{
cwarning('找不到模板变量:', $name );
}
if (! empty ( $args ))
{
$r = $this -> $method_name ( $args [0]);
}
else
{
$r = $this -> $method_name ();
}
return $r ;
}
public function get_test( $op )
{
return 'hello world!';
}
}
|
登入後複製
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | <html>
<body>
<?php
$o = new template();
$tpl = $o ->main();
$test = $tpl ->test();
?>
<div><?php echo $test ; ?></div>
</body>
</html>
|
登入後複製