【问题标题】:Help with my PHP template class帮助我的 PHP 模板类
【发布时间】:2011-02-12 22:52:06
【问题描述】:

我想在我的项目中将HTML的输出与我的程序代码分开,所以我写了一个非常简单的数据库类。

<?php
class Template
{
    private $template;

    function load($filePath)
    {
        if(!$this->template = file_get_contents($filePath))
            $this->error('Error: Failed to open <strong>' . $filePath . '</strong>');
    }

    function replace($var, $content)
    {
        $this->template = str_replace("{$var}", $content, $this->template);
    }

    function display()
    {
        echo $this->template;
    }

    function error($errorMessage)
    {
        die('die() by template class: <strong>' . $errorMessage . '</strong>');
    }
}
?>

我需要帮助的是display() 方法。比如说我使用这个代码:

$tplObj = new Template();
$tplObj->load('index.php');
$tplObj->replace('{TITLE}', 'Homepage');
$tplObj->display();

index.php 文件是这样的:

<html>
    <head>
        <title>{TITLE}</title>
    </head>
    <body>
        <h1>{TITLE}</h1>
        <?php
            if($something) {
                echo '$something is true';
            } else {
                echo '$something is false';
            }
        ?>
    </body>
</html>

我只是想知道那里的 PHP 代码是否会运行?还是只是作为纯文本发送到浏览器?我在我的模板类中使用eval(),但我讨厌那个功能:P

谢谢。

【问题讨论】:

  • 你为什么不试试运行它?
  • 我还想收集有关我应该使用什么来让包含文件中的 PHP 运行的建议。

标签: php class templates


【解决方案1】:

没有。它会输出纯文本。

'echo' 输出而不解析 PHP 代码。

您无需依赖使用 eval。还有其他方法,例如使用输出缓冲。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-01-20
    • 1970-01-01
    • 2015-05-09
    • 2011-10-27
    • 1970-01-01
    • 2017-06-25
    • 2016-07-06
    相关资源
    最近更新 更多