Sticky Posts
Apr 7, 2009
Eval For Inline PHP Inside HTML
Eval is real cool and can give a lot more versatility to a coder. Eval for PHP has a small functionality issue one beginner would not expect. If you eval, the parameter has to be a PHP code string. But if you have HTML and inline PHP code, there's a catch.
eval("<b>cool <?=' stuff'?></b>");
If you try to eval the above it will fail as it's not PHP code. It's HTML with PHP inside. And, as eval evaluates the expression as if it was executed in the place where it's called, this eval will never work. On the other hand this will work:
eval("echo 'stuff';");
This can be evaled easily no matter what. It's only PHP code, the whole point of EVAL.
But how do you eval HTML with inline PHP?
You need to use this method:
eval(' ?>'.$html_with_php_inline.'<?php ');
As you can see you need to close the current PHP block (before eval), append the HTML + PHP blocks and then reopen the PHP tag (after eval) to continue. There are spaces there you might miss:
eval('[space]?>'/*<--Close Block*/ . $html_with_php_inline . /*Reopen Block-->*/'<?php[space]');
So the functional example is actually:
eval(' ?>'."<b>cool <?=' stuff'?></b>".'<?php '); // Don't forget the spaces
What Is This Good For?
It's good for writing PHP + HTML in a textarea and eventually have it evaled. I have a plugin that overrides all RAW 'Stock' Wordpress TEXT Widgets and EVAL's them. So I can add PHP blocks in the HTML code of the Widgets ... and most have (*** HINT: Look at the source of this page and you'll see a funny JS escaped block. That is done using a Text Widget and output buffering it using a JS encoder I have and all is done in the Wordpres Widgets panel. Including the encoding. ***).
I'll publish it someday :)
The bad idea you might just have ;)
Some may be tempted to ease their life by writing the evalex function like this:
function evalex($evaled){ return eval(' ?>'.$evaled.'<?php'); }
Bad boy! Eval acts as evaled code is inline. This function will work but, if you do this, you loose variable scope of calling code. Example:
$scoped_var = '.'; // This is a dot
eval(' ?>['.'<?=$scoped_var;?>'.']<?php '); // A [.] should appear using classic eval
evalex('[<?=$scoped_var;?>]'); // A [] will appear using 'smart' eval as $scoped_var is outside scope
evalex('[<?php global $scoped_var; echo $scoped_var;?>]'); // A [.] will appear using 'smart' eval as $scoped_var is outside scope ... you need to use global $scoped_var;
Piece of cake. Start evaling now!

