PHP interpolating string for function output

亡梦爱人 提交于 2019-12-19 05:11:20

问题


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?


回答1:


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.




回答2:


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.




回答3:


Unless interpolation is absolutely necessary (please comment and let me know why), concatenate the function output with the string.

$s =  "foo " . bar();

Source: 1.8. Interpolating Functions and Expressions Within Strings



来源:https://stackoverflow.com/questions/10758537/php-interpolating-string-for-function-output

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!