Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP interpolating string for function output

Tags:

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?

like image 651
Ryan Avatar asked May 25 '12 17:05

Ryan


People also ask

Does PHP have string interpolation?

PHP String formatting String interpolationYou can also use interpolation to interpolate (insert) a variable within a string. Interpolation works in double quoted strings and the heredoc syntax only. $name = 'Joel'; // $name will be replaced with `Joel` echo "<p>Hello $name, Nice to see you.

How do you call a function from a string in PHP?

To call a function from a string stored in a variable, use $func.

Which strings do interpolate variables?

String interpolation is common in many programming languages which make heavy use of string representations of data, such as Apache Groovy, Julia, Kotlin, Perl, PHP, Python, Ruby, Scala, Swift, Tcl and most Unix shells.

What do you meant by interpolating variables in double quoted strings?

When you define a string literal using double quotes or a heredoc, the string is subject to variable interpolation. Interpolation is the process of replacing variable names in the string with the values of those variables.


1 Answers

It is absolutely possible using the string-to-function-name calling technique as Overv's answer indicates. In many trivial substitution cases it reads far better than the alternative syntaxes such as

"<input value='<?php echo 1 + 1 + foo() / bar(); ?>' />" 

You need a variable, because the parser expects the $ to be there.

This is where the identity transform works well as a syntactic hack. Just declare an identity function, and assign the name to a variable in scope:

function identity($arg){return $arg;} $interpolate = "identity"; 

Then you can pass any valid PHP expression as the function argument:

"<input value='{$interpolate(1 + 1 + foo() / bar() )}' />" 

The upside is that you can eliminate a lot of trivial local variables and echo statements.

The downside is that the $interpolate variable falls out of scope, so you would have to repeatedly declare it global inside of functions and methods.

like image 88
jerseyboy Avatar answered Sep 22 '22 17:09

jerseyboy