A mostly unknown perhaps useless but sorta neat PHP coding trick

Yesterday while documenting that PHP 6 deprecates $string{42} in favor of $string[42] I stumbled upon a comment within the PHP Manual XML sources, and here it is in its entirety:

<!-- maybe it's better to leave this out?? 
// this works, but i disencourage its use, since this is NOT 
// involving functions, rather than mere variables, arrays and objects.
$beer = 'Heineken';
echo "I'd like to have another {${ strrev('reeb') }}, hips";
 -->

The thought of a function being called from within a string (without eval()) seems a little odd, doesn’t it? Well, the above code in fact works. Not sure how useful it is but likely someone will find a creative use or two. The internals team generally feels that the behavior isn’t worth documenting as it’s simply an ugly and poor coding style BUT, maybe you’ll see it (the “{${ func() }}” syntax) on a PHP exam somewhere so now you know… :-)

History: This information was added within a patch titled “Added jeroen’s updates” by Damien Seguy apparently for Jeroen van Wolffelaar on the date Thu May 10 18:01:04 2001 UTC.

Update (April 20, 2007): A few days ago Jani demonstrated a simpler example for these variable functions:

$exec = ‘shell_exec’;

$cmd = ‘ls -l’;

echo “This is embedded exec: {$exec($cmd)}”;

5 thoughts on “A mostly unknown perhaps useless but sorta neat PHP coding trick”

  1. It gets way better:
    $a = array(1, 2, 3, 4, 4 => ‘beer’);
    echo “I want {$a[“{$a[“{$a[“{$a[“{$a[0]}”]}”]}”]}”]}!\n”

  2. Never have I been se grateful that a feature was _not_ published. You can only imagine what “uses” the folks over at strrev(‘bbphp’) would have found for this “feature”

  3. I think you are missing the point. I, for one, had no idea that you could call functions directly from a string.

    $ab = ‘6’;

    echo “ab: {${exit}}”;

    Just another way to call eval(), I guess. And actually that’s exactly what it is:

    echo “ab: {${;}}”;

    Parse error: parse error, unexpected ‘;’ in xx : *eval()’d code* on line x;

Leave a Reply

Your email address will not be published. Required fields are marked *