Ryan Ryan - 6 months ago 9
PHP Question

PHP interpolating string for function output

PHP support variable interpolation in double quoted strings, e.g.

$s = "foo $bar";


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

e.g.

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


Something like that? Seems not possible right?

Answer

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.

Comments