【问题标题】:PHP include class functions with variablesPHP 包含带变量的类函数
【发布时间】:2009-05-19 10:07:00
【问题描述】:

我正在尝试使用变量来获取扩展类中的函数,这是我想要做的,但我无法让它工作,谢谢你的帮助。

class topclass {
    function mode() {
        $mode = 'function()';

        $class = new extendclass;
        $class->$mode;
    }
}

【问题讨论】:

    标签: php class variables


    【解决方案1】:

    $mode 变量中不要包含方括号“()”。

    class topclass {
        function mode() {
            $mode = 'functionx';
    
            $class = new extendclass;
            $class->$mode();
        }
    }
    

    【讨论】:

      【解决方案2】:

      您还可以使用回调,它是实例的数组元组和命名函数的字符串。如果预期的调用是 $foo->bar(),那么回调将是:

      $callback = array($foo, 'bar');
      

      常规函数(不是方法)和静态方法存储为纯字符串:

      // Function bar
      $callback = 'bar';
      // Static method 'bar' in class Foo
      $callback = 'Foo::bar';
      

      使用 call_user_func 或 call_user_func_array 调用,第二个允许参数传递给回调函数:

      // No parameters
      call_user_func($callback);
      // Parameters 'baz' and 'bat'
      call_user_func_array($callback, array('baz', 'bat');
      

      这似乎是不必要的复杂化,但在许多情况下,您可能希望能够以编程方式构建函数调用,或者您可能提前不知道将传递给函数的参数数量(有些函数,例如 array_merge 和 sprintf 允许可变数量的参数)。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2011-09-19
        • 2013-05-17
        • 2013-12-18
        • 2018-12-29
        • 2023-04-06
        • 2018-07-05
        • 1970-01-01
        相关资源
        最近更新 更多