2010-04-27 39 views
0

我想在我的項目中將HTML輸出與我的程序代碼分開,所以我編寫了一個非常簡單的數據庫類。幫助我的PHP模板類

<?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

謝謝。

+1

你爲什麼不嘗試運行它? – dclowd9901 2010-04-27 16:12:24

+0

我也想收集有關我應該如何讓PHP在包含文件中運行的建議。 – blerh 2010-04-27 16:38:33

回答

1

不會。它會出來純文本。

'echo'輸出沒有解析PHP代碼。

您不需要再使用eval。還有其他一些方法,例如使用輸出緩衝。