【问题标题】:PHP calling class function dynamically by variables caughts exceptionPHP通过变量动态调用类函数捕获异常
【发布时间】:2018-04-10 16:59:44
【问题描述】:

我正在尝试使用变量 (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 之前的'$'。我尝试了几种变体,但 $view_profile 的错误始终存在。这种方法有什么问题?

【问题讨论】:

    标签: php function variables dynamically-generated


    【解决方案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;
    

    【讨论】:

    • 伟大的西尔维奥!这是缺少的东西,我在显示器前 10 小时后还没有看到!谢谢
    • Silvio,是否也可以这样设置公共类变量?我的意思是像 $foo->$var 这样的通用变量?如何以这种方式使用 $var 设置类变量?
    • 是的,当然,它的工作原理完全相同: $varname = "foo"; $this->$varname = "bar"; // 现在 $this->foo == "bar";
    猜你喜欢
    • 2013-04-29
    • 1970-01-01
    • 2019-08-22
    • 1970-01-01
    • 2012-04-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多