PHP通过变量动态调用类函数异常

时间:2018-04-10 16:59:44

标签: php function variables dynamically-generated

我试图用变量(php7)调用类的公共函数。因此,我做了:

$module = 'frontend\\modules\\rest\\models\\Member';
$action = 'view_profile'

$response = new $module();
$response = $response1->$action;

通过调用$ response1-> $ action,我收到以下错误:

Undefined property: frontend\modules\rest\models\Member::$view_profile

我看到系统试图调用... Member \ $ view_profile,这不起作用。但为什么在view_profile之前是'$'。我已经尝试了几个variantes,但$ view_profile的错误始终存在。这种方法有什么问题?

1 个答案:

答案 0 :(得分:1)

查看此其他回复:OOP in PHP: Class-function from a variable?(无法发表评论,抱歉......)

无论如何,这就是你所追求的:http://php.net/manual/en/functions.variable-functions.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()

?>

所以我想唯一缺少的是

之后的“()”
$response1->$action;