English 中文(简体)
函数输出的PHP插值字符串
原标题:PHP interpolating string for function output

PHP支持双引号字符串中的变量插值,例如,

$s = "foo $bar";

但是,是否有可能在双引号字符串中插值函数调用结果?

例如

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

像那样?这似乎不可能,对吧?

最佳回答

PHP中的双引号功能不计算PHP代码,它只是用变量的值替换变量。如果你想动态地评估PHP代码(非常危险),你应该使用eval

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

或者,如果你只是想创建一个函数:

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

只有在真的没有其他选择的情况下才使用它。

问题回答

使用字符串函数名称调用技术作为Overv s answer表示。在许多琐碎的替换情况下,它的阅读效果比其他语法要好得多,例如

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

您需要一个变量,因为解析器希望$在那里。

这就是身份转换作为一种语法破解很好地工作的地方。只需声明一个标识函数,并将其名称赋给作用域中的一个变量:

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

然后,您可以将任何有效的PHP表达式作为函数参数传递:

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

好处是,您可以消除大量琐碎的局部变量和返回语句。

缺点是$interpole变量超出了作用域,因此您必须在函数和方法内反复声明它是全局的。

除非插值是绝对必要的(请说明原因),否则将函数输出与字符串连接起来。

$s =  "foo " . bar();

You can t do that. However, as proposed in this answer, you can trick the constraint by having a function as variable, or in my case, an instance of a home-made class :

class StringInterpolatorWrapper
{
    public function i(mixed $message): mixed
    {
        return $message;
    }
}

$f = new StringInterpolatorWrapper();
$complex_string = <<<HTML
<input value="{$f->i(1 + 1 + foo() / bar())}" />
HTML;

无论你在哪里需要它,只需导入类并创建一个实例。

您可以向该类添加其他方法,以满足您的需求,为{$f->;i(my_function($my_var))}中常用的函数创建快捷方式。





相关问题
Simple JAVA: Password Verifier problem

I have a simple problem that says: A password for xyz corporation is supposed to be 6 characters long and made up of a combination of letters and digits. Write a program fragment to read in a string ...

Case insensitive comparison of strings in shell script

The == operator is used to compare two strings in shell script. However, I want to compare two strings ignoring case, how can it be done? Is there any standard command for this?

Trying to split by two delimiters and it doesn t work - C

I wrote below code to readin line by line from stdin ex. city=Boston;city=New York;city=Chicago and then split each line by ; delimiter and print each record. Then in yet another loop I try to ...

String initialization with pair of iterators

I m trying to initialize string with iterators and something like this works: ifstream fin("tmp.txt"); istream_iterator<char> in_i(fin), eos; //here eos is 1 over the end string s(in_i, ...

break a string in parts

I have a string "pc1|pc2|pc3|" I want to get each word on different line like: pc1 pc2 pc3 I need to do this in C#... any suggestions??

Quick padding of a string in Delphi

I was trying to speed up a certain routine in an application, and my profiler, AQTime, identified one method in particular as a bottleneck. The method has been with us for years, and is part of a "...

热门标签