是否可以像这样调用类中的函数:
$class = new class;
$function_name = "do_the_thing";
$req = $class->$function_name();
Run Code Online (Sandbox Code Playgroud)
类似的解决方案,这似乎不起作用?
Sar*_*raz 58
是的,有可能,就像变量函数一样,看看这个.
来自PHP官方网站的示例:
<?php
class Foo
{
function Variable()
{
$name = 'Bar';
$this->$name(); // This calls the Bar() method
}
function Bar()
{
echo "This is Bar";
}
}
$foo = new Foo();
$funcname = "Variable";
$foo->$funcname(); // This calls $foo->Variable()
?>
Run Code Online (Sandbox Code Playgroud)
在您的情况下,请确保该功能do_the_thing
存在.另请注意,您正在存储函数的返回值:
$req = $class->$function_name();
Run Code Online (Sandbox Code Playgroud)
尝试查看变量$req
包含的内容.例如,这应该给你信息:
print_r($req); // or simple echo as per return value of your function
Run Code Online (Sandbox Code Playgroud)
注意:
变量函数不适echo(), print(), unset(), isset(), empty(), include(), require()
用于诸如此类的语言结构.利用包装函数将这些结构中的任何一个用作可变函数.
我最简单的例子是:
$class = new class;
$function_name = "do_the_thing";
$req = $class->${$function_name}();
Run Code Online (Sandbox Code Playgroud)
$ {$ function_name}就是诀窍
也适用于静态方法:
$req = $class::{$function_name}();
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
25356 次 |
最近记录: |