【发布时间】:2011-02-09 02:10:23
【问题描述】:
是否可以像这样从类中调用函数:
$class = new class;
$function_name = "do_the_thing";
$req = $class->$function_name();
类似的解决方案,这似乎不起作用?
【问题讨论】:
是否可以像这样从类中调用函数:
$class = new class;
$function_name = "do_the_thing";
$req = $class->$function_name();
类似的解决方案,这似乎不起作用?
【问题讨论】:
您可以使用ReflectionClass。
示例:
$functionName = 'myMethod';
$myClass = new MyClass();
$reflectionMyMethod = (new ReflectionClass($myClass))->getMethod($functionName);
$relectionMyMethod->invoke($myClass); // same as $myClass->myMethod();
如果方法不存在,记得捕获 ReflectionException。
【讨论】:
我最简单的例子是:
$class = new class;
$function_name = "do_the_thing";
$req = $class->${$function_name}();
${$function_name}是诀窍
也适用于静态方法:
$req = $class::{$function_name}();
【讨论】:
是的,有可能,即变量函数,有一个look at this.
来自 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()
?>
在您的情况下,请确保函数 do_the_thing 存在。另请注意,您正在存储函数的返回值:
$req = $class->$function_name();
尝试查看变量$req 包含什么。例如,这应该给你信息:
print_r($req); // or simple echo as per return value of your function
注意:
变量函数不适用于echo(), print(), unset(), isset(), empty(), include(), require() 等语言结构。利用包装函数将这些结构中的任何一个用作变量函数。
【讨论】: