tags:

views:

65

answers:

1

I have this code:

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

In the $template_layout variable is a call for the variable $output_template, so then the script moves onto the $output_template variable

But it doesn't go any further, inside the $output_template is a call to the variable $box, but it doesn't go any further than one level

+2  A: 

I would never want nested eval(), and especially not in any recursive logic. Bad news. Use PHP's Include instead. IIRC eval() creates a new execution context, with overhead whereas include() doesn't.

If you have buffers such as:

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

I sometimes have files like Index.tpl such as above that access an associative array like this, then you just do in your class:

<?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 */
           ...

Checkout ob_start() and other output buffer controls

If you do use eval() or any kind of user data inclusion, be super safe about sanitizing inputs for bad code.

It looks like you are writing a combined widget/template system of some kind. Write your widgets (views) as classes and allow them to be used in existing template systems. Keep things generic with $myWidget->render($model) and so on.

I saw this on the PHP doc-user-comments-thingy and it seems like a bad idea:

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

Perhaps someone can enlighten me on that one :P

Aiden Bell
include is exactly the same as eval(file_get_contents)
stereofrog
@stereofrog - functionally maybe, but speed?
Aiden Bell
obviously, eval is faster, because it doesn't involve disk IO
stereofrog
@sterofrog, what ... file_get_contents() does have the I/O overhead,just in a different place.
Aiden Bell