PHP中的OOP:来自变量的类函数? [英] OOP in PHP: Class-function from a variable?

查看:66
本文介绍了PHP中的OOP:来自变量的类函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以从这样的类中调用函数:

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?

推荐答案

是的,有可能,也就是变量函数,具有

Yes, it is possible, that is know as variable functions, have a 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存在.还要注意,您正在存储函数的返回值:

In your case, make sure that the function do_the_thing exists. Also note that you are storing the return value of the function:

$req = $class->$function_name();

尝试查看变量$req包含什么.例如,这应该为您提供信息:

Try to see what the variable $req contains. For example this should give you info:

print_r($req); // or simple echo as per return value of your function

注意:

变量功能不适用于echo(), print(), unset(), isset(), empty(), include(), require()之类的语言构造.利用包装器函数将这些构造中的任何一个用作变量函数.

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.

这篇关于PHP中的OOP:来自变量的类函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆