PHP 中的 OOP:来自变量的类函数?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2657454/
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
OOP in PHP: Class-function from a variable?
提问by Martti Laine
Is it possible to call functions from class like this:
是否可以像这样从类调用函数:
$class = new class;
$function_name = "do_the_thing";
$req = $class->$function_name();
Something similar solution, this doesn't seem to work?
类似的解决方案,这似乎不起作用?
回答by Sarfraz
Yes, it is possible, that is know as variable functions, have a look at this.
是的,这是可能的,也就是所谓的变量函数,看看这个。
Example from PHP's official site:
来自 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()
?>
In your case, make sure that the function do_the_thingexists. Also note that you are storing the return value of the function:
在您的情况下,请确保该功能do_the_thing存在。另请注意,您正在存储函数的返回值:
$req = $class->$function_name();
Try to see what the variable $reqcontains. For example this should give you info:
尝试查看变量$req包含的内容。例如,这应该为您提供信息:
print_r($req); // or simple echo as per return value of your function
Note:
笔记:
Variable functions won't work with language constructs such as echo(), print(), unset(), isset(), empty(), include(), require()and the like. Utilize wrapper functions to make use of any of these constructs as variable functions.
变量函数不适用于诸如echo(), print(), unset(), isset(), empty(), include(), require()之类的语言结构。利用包装函数将这些构造中的任何一个用作变量函数。
回答by Tudor
My easiest example is:
我最简单的例子是:
$class = new class;
$function_name = "do_the_thing";
$req = $class->${$function_name}();
${$function_name}is the trick
${$function_name}是诀窍
Also works with static methods:
也适用于静态方法:
$req = $class::{$function_name}();
回答by user2986600
You can use ReflectionClass.
您可以使用ReflectionClass.
Example:
例子:
$functionName = 'myMethod';
$myClass = new MyClass();
$reflectionMyMethod = (new ReflectionClass($myClass))->getMethod($functionName);
$relectionMyMethod->invoke($myClass); // same as $myClass->myMethod();
Remember to catch ReflectionException If Method Not Exist.
如果方法不存在,请记住捕获 ReflectionException。

