首頁 > php教程 > PHP源码 > 先识别标签后计算的模板思路

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

PHP中文网
發布: 2016-05-25 17:13:23
原創
1118 人瀏覽過

传统模板引擎的思路是:计算模板变量->设置模板变量(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 = &#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;;

}

}

登入後複製

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>

登入後複製
本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
作者最新文章
熱門推薦
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板