【问题标题】:How do you eval() a PHP code through multiple levels?你如何通过多个级别 eval() 一个 PHP 代码?
【发布时间】:2010-01-30 20:22:51
【问题描述】:

我有这个代码:

$layout_template = template_get("Layout");
$output_template = template_get("Homepage");
$box = box("Test","Test","Test");
eval("\$output = \"$layout_template\";");
echo $output;

在 $template_layout 变量中调用 变量 $output_template,然后脚本移动到 $output_template 变量

但它不会更进一步,在 $output_template 内部是对变量 $box 的调用,但它不会更进一步

【问题讨论】:

  • 每次调用 eval() 都会有一个天使死去。
  • 作为一般规则,您不要使用 eval(); eval 有一些正当的理由,但它们很少。
  • @Aiden:如果你在循环中调用eval(),那就是天使种族灭绝!
  • 那你用什么代替eval呢?
  • 在你的情况下,一个简单的包含就足够了......

标签: php eval


【解决方案1】:

我从不想要嵌套eval(),尤其是在任何递归逻辑中。坏消息。请改用PHP's Include。 IIRC eval() 创建一个新的执行上下文,有开销,而 include() 没有。

如果您有以下缓冲区:

<h1><?php echo $myCMS['title']; ?></h1>

我有时有像上面这样的文件 Index.tpl 访问这样的关联数组,然后你就在你的课堂上做:

<?php
   class TemplateEngine {
       ...
       public function setvar($name, $val)
       {
            $this->varTable[$name]=make_safe($val);
       }

       ....
       /* Get contents of file through include() into a variable */
       public function render( $moreVars )
       {
           flush();
           ob_start();
           include('file.php');
           $contents = ob_get_clean();
           /* $contents contains an eval()-like processed string */
           ...

结帐ob_start() and other output buffer controls

如果您确实使用 eval() 或任何类型的用户数据包含,请在清理输入以发现错误代码时非常安全。

看起来您正在编写某种组合的小部件/模板系统。将您的小部件(视图)编写为类,并允许它们在现有的模板系统中使用。使用$myWidget-&gt;render($model) 等保持通用性。

我在 PHP doc-user-cmets-thingy 上看到了这个,这似乎是个坏主意:

<?php
$var = 'dynamic content';
echo eval('?>' . file_get_contents('template.phtml') . '<?');
?>

也许有人可以启发我:P

【讨论】:

  • @stereofrog - 功能上可能,但速度?
  • @sterofrog,什么... file_get_contents() 确实有 I/O 开销,只是在不同的地方。
猜你喜欢
  • 2017-09-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多