PHP-从字符串执行PHP

PHP-从字符串执行PHP,php,Php,这个有点奇怪。我创建了一个函数,用于选择模板并包含它或分析%0、%1、%3等变量。这是当前的功能: if(!fopen($tf,"r")){ $this->template("error",array("404")); } $th = fopen($tf,"r"); $t = fread($th, filesize($tf) ); $i=0; for($i;$i<count($params);$i++){ $i2 = '%' . $i; $t = str_re

这个有点奇怪。我创建了一个函数,用于选择模板并包含它或分析%0、%1、%3等变量。这是当前的功能:

if(!fopen($tf,"r")){
    $this->template("error",array("404"));
}
$th = fopen($tf,"r");
$t = fread($th, filesize($tf) );
$i=0;
for($i;$i<count($params);$i++){
    $i2 = '%' . $i;
    $t = str_replace($i2,$params[$i],$t);
}
echo $t . "\n";
fclose($th);
if(!fopen($tf,“r”)){
$this->template(“error”,数组(“404”);
}
$th=fopen($tf,“r”);
$t=fread($th,filesize($tf));
$i=0;

对于($i;$i,正如我在评论中所说,我认为像Smarty这样的模板引擎可能会更好地为您服务,但下面是我如何使用输出缓冲而不是
eval()

像这样的

ob_start();
include "your_template_file.php";
$contents = ob_get_contents();  // will contain the output of the PHP in the file
ob_end_clean();

// process your str_replace() variables out of $contents

如果您找不到其他解决方案,则
eval()
将在模板中执行PHP代码。这是最终的解决方案!即使如此,如果您使用它,您也会遇到一些麻烦。为什么不使用一个现成的模板引擎呢?谢谢:)我不想使用smarty的原因是我想创建自己的简单模板解析器,以便在将来的项目中使用