php 在PHP中,如何在字符串中调用函数?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10002652/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 21:07:31  来源:igfitidea点击:

In PHP, How to call function in string?

php

提问by lovespring

say,string is:

说,字符串是:

$str="abcdefg foo() hijklmopqrst";

How to let php call foo() and insert the return string to this string?

如何让 php 调用 foo() 并将返回字符串插入到这个字符串中?

采纳答案by Basti

$str="abcdefg foo() hijklmopqrst";
function foo() {return "bar";}

$replaced = preg_replace_callback("~([a-z]+)\(\)~", 
     function ($m){
          return $m[1]();
     }, $str);

output:

输出:

$replaced == 'abcdefg bar hijklmopqrst';

This will allow any lower-case letters as function name. If you need any other symbols, add them to the pattern, i.e. [a-zA-Z_].

这将允许任何小写字母作为函数名称。如果您需要任何其他符号,请将它们添加到模式中,即[a-zA-Z_].

Be VERYcareful which functions you allow to be called. You should at least check if $m[1] contains a whitelisted function to not allow remote code injection attacks.

非常小心,它的功能你允许调用。您至少应该检查 $m[1] 是否包含列入白名单的函数以不允许远程代码注入攻击。

$allowedFunctions = array("foo", "bar" /*, ...*/);

$replaced = preg_replace_callback("~([a-z]+)\(\)~", 
     function ($m) use ($allowedFunctions) {
          if (!in_array($m[1], $allowedFunctions))
              return $m[0]; // Don't replace and maybe add some errors.

          return $m[1]();
     }, $str);

Testrun on "abcdefg foo() bat() hijklmopqrst"outputs "abcdefg bar bat() hijklmopqrst".

"abcdefg foo() bat() hijklmopqrst"输出进行测试运行"abcdefg bar bat() hijklmopqrst"

Optimisation for whitelisting approach (building pattern dynamically from allowed function names, i.e. (foo|bar).

白名单方法的优化(从允许的函数名称动态构建模式,即(foo|bar).

$allowedFunctions = array("foo", "bar");

$replaced = preg_replace_callback("~(".implode("|",$allowedFunctions).")\(\)~", 
     function ($m) {
          return $m[1]();
     }, $str);

回答by HonoredMule

If you're calling a method of some class, you can use normal variable expansion. For example:

如果您正在调用某个类的方法,则可以使用普通的变量扩展。例如:

<?php
class thingie {

  public function sayHello() {
    return "hello";
  }

}

$t = new thingie();
echo "thingie says: {$t->sayHello()}";

This will output:

这将输出:

thingie says: hello

thingie 说: 你好

Note that the braces around the call arerequired.

请注意,调用周围的大括号必需的。

回答by Frederick Marcoux

Just use this:

只需使用这个:

$str = "abcdefg".foo()."hijklmnopqrstuvwxyz";

It will call function during string creation.

它将在字符串创建期间调用函数。

回答by v.babak

function foo()
{
    return 'Hi';
}
$my_foo = 'foo';
echo "{$my_foo()}";

回答by savinger

$foo = foo();
$str = "abcdefg {$foo} hijklmopqrst";

回答by Valerio Bozz

To get arbitrary expressions being evaluated from a double-quoted string you can speculate on variable-functions:

要从双引号字符串计算任意表达式,您可以推测变量函数:

<?php
// A user function
function foo() {
    return 'bar';
}

/**
 * The hack
 *
 * @param $v mixed Value
 * return mixed Value (untouched)
 */
$_ = function ( $v ) {
    return $v;
};

// Happy hacking
echo "Foo is {$_( foo() )} and the sum is {$_( 41 + 1 )}...{$_( str_repeat( ' arrh', 3 ) )}!";

Result:

结果:

Foo is bar and the sum is 42... arrrh arrrh arrrh!

References:

参考:

回答by Mubashar

Its still not possible, There are hacks available but not what I would recommend rather suggest to stick with old school dot operator i.e. $str="abcdefg ". foo() ." hijklmopqrst";

它仍然不可能,有可用的黑客攻击,但不是我推荐的,而是建议坚持使用老式点运算符,即 $str="abcdefg ". foo() ." hijklmopqrst";

As per the Complex (curly) syntax documentation

根据复杂(卷曲)语法文档

Note:
Functions, method calls, static class variables, and class constants inside {$} work since PHP 5. However, the value accessed will be interpreted as the name of a variable in the scope in which the string is defined. Using single curly braces ({}) will not work for accessing the return values of functions or methods or the values of class constants or static class variables.

注意:
函数、方法调用、静态类变量和 {$} 中的类常量从 PHP 5 开始工作。但是,访问的值将被解释为定义字符串的范围内的变量名称。使用单花括号 ({}) 不能用于访问函数或方法的返回值或类常量或静态类变量的值。