用include来处理模板的问题

    /**
     * 测试方法
      */
    protected function getHtml()
    {
        $tpl = $this->pageletDir.$this->plTemplate;
        $html=include($tpl);
        return $html;
    }
    protected function getHtml()
    {
        $tpl = $this->pageletDir.$this->plTemplate;
        ob_start();
        include($tpl);
        $html=ob_get_contents();
        ob_end_clean();
        return $html;
    }

 

之前对于include方法包含模板文件的处理不是很清楚,也就对上面的第二种代码产生过疑问,认为为什么不用第一种方法?

说明:模板内容就是普通的html。

 

试验后发现:第一种方法并不能帮助我们完成想要的包含模板的功能,$html不是加载后的模板内容,而是 1 。

 

 

先放下问题,来看看php手册上的例子:

return.php
<?php
$var = 'PHP';
return $var;
?>
noreturn.php
<?php
$var = 'PHP';
?>

testreturns.php
<?php
$foo = include 'return.php';
echo $foo; // prints 'PHP'
$bar = include 'noreturn.php';
echo $bar; // prints 1

?>

 

$bar 的值为 1 是因为 include 成功运行了。注意以上例子中的区别。第一个在被包含的文件中用了 return 而另一个没有。

如果在包含文件中定义有函数,这些函数不管是在 return 之前还是之后定义的,都可以独立在主文件中使用。

 

这下明白了吧? 对于include的使用又可以增进一步了!

 

所以在包含模板时,一般情况下,我们都要使用最开始两个例子的第二个:使用输出控制函数来进行模板的处理。

posted @ 2013-06-24 18:00  Gcoder  阅读(606)  评论(0编辑  收藏  举报