Functions in strings with PHP as templates

Although you can use variables within strings in PHP, you can’t do functions. Well, not quite. If your function name begins with a dollar sign ($), it works fine. You can exploit this to call non-object functions such as htmlspecialchars.

$F = "F";
function F($s) { return $s; }
$filename = '';
echo "{$F(htmlspecialchars($filename))}";

It’s still not as clean as if you had separated application logic and presentation code like you should have. I really don’t recommend doing this, but it’s an interesting approach.


3 Responses to Functions in strings with PHP as templates

  1. I always thought you could do this anyway.. O_o


  2. Nah.

    “{htmlspecialchars($var)}” won't work.


Leave a Reply

Your email address will not be published.

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>