【问题标题】:PHP: call dynamic function, but in a class?PHP:调用动态函数,但在一个类中?
【发布时间】:2011-01-11 04:32:23
【问题描述】:

我正在尝试创建一个初始化函数,它将调用类中的多个函数,最终结果的一个简单示例如下:

$foo = new bar;
$foo->call('funca, do_taxes, initb');

这可以正常使用 call_user_func 函数,但我真正想做的是在类中执行此操作,我不知道如何执行此操作,我的无效代码的快速示例如下:

class bar {
   public function call($funcs) {
       $funcarray = explode(', ', $funcs);
       foreach($funcarray as $func) {
          call_user_func("$this->$func"); //???
       }
   }
   private function do_taxes() {
       //...
   }
}

如何调用动态类函数?

【问题讨论】:

    标签: php oop class


    【解决方案1】:

    你需要使用一个数组,比如Example #4 in the manual:

    call_user_func(array($this, $func));
    

    【讨论】:

    • +1。我更喜欢call_user_func()call_user_func_array() 而不是$this->$func()
    【解决方案2】:

    它实际上比你想象的要简单得多,因为 PHP 允许 variable variables 之类的东西(以及变量对象成员名称):

    foreach($funcarray as $func) {
        $this->$func();
    }
    

    【讨论】:

    • 谢谢 Amber,我很高兴现在可以连接到两个并完成我的脚本。
    【解决方案3】:

    你需要做的就是

    $this->$func();
    

    编辑 - 忽略上一篇文章,我有点仓促和误解

    您可以对本机或用户函数执行类似的操作来代替 call_user_func

    function arf($a) {print("arf $a arf");}
    
    $x = 'strlen';
    $f2 = 'arf';
    
    print($x('four')."\n");
    $f2($arg1);
    

    输出

    4
    arf  arf 
    

    【讨论】:

      【解决方案4】:

      当我们要检查类中是否存在类函数/方法时,

      那么这可能会有所帮助

      课内...

       $class_func = "foo";
      
       if(method_exists($this , $class_func ) ){
          $this->$class_func();
        }
      
       public function foo(){
         echo " i am called ";
       }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-07-17
        • 2013-08-10
        • 1970-01-01
        • 1970-01-01
        • 2018-04-22
        • 1970-01-01
        相关资源
        最近更新 更多