Search code examples
phpstringstring-interpolation

PHP interpolating string for function output


PHP supports variable interpolation in double quoted strings, for example,

$s = "foo $bar";

But is it possible to interpolate function call results in the double quoted string?

For example,

$s = "foo {bar()}";

Something like that? It doesn't seem not possible, right?


Solution

  • The double quote feature in PHP does not evaluate PHP code, it simply replaces variables with their values. If you want to actually evaluate PHP code dynamically (very dangerous), you should use eval:

    eval( "function foo() { bar() }" );
    

    Or if you just want to create a function:

    $foo = create_function( "", "bar()" );
    $foo();
    

    Only use this if there really is no other option.