dongwei1855 2014-11-18 21:27
浏览 83
已采纳

call_user_func_array()args,字符串作为匹配函数args名称的键

At the moment I have something like this

function callFunction($method, $args) {
    if(method_exists($this, $method)) {
            call_user_func_array(array($this, $method), $args);
    }
}

function myfunction ($hello, $world, $blah) {
}

where $args is an array like [0] => 'string1', [1] => 'string2', [2] => 'string3' which gets passed to the function in that order. However would there be a way to have the keys to the args match the functions argument names. like ['hello'] => 'string1', ['world'] => 'string2', ['blah'] => 'string3' where they could be in any order and be matched to the correct argument name by key?

  • 写回答

1条回答 默认 最新

  • dspvin19712 2014-11-18 22:06
    关注

    Quite some overhead, but possible:

    function callFunction($method, $args) {
        if(method_exists($this, $method)) {
             $arguments = array();
             $reflectionmethod = new ReflectionMethod($this,$method);
             foreach($reflectionmethod->getParameters() as $arg){
                 if(isset($args[$arg->name])){
                     $arguments[$arg->name] = $args[$arg->name];
                 } else if($arg->isDefaultValueAvailable()){
                     $arguments[$arg->name] = $arg->getDefaultValue();
                 } else {
                     $arguments[$arg->name] = null;
                 }
             }
             call_user_func_array(array($this, $method), $arguments);
        }
    }
    
    function myfunction ($hello, $world, $blah) {
    }
    

    Something that is passed by reference would be iffy though. You'd probably need some more code to make that work. Long story short: PHP ain't Python :)

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 多址通信方式的抗噪声性能和系统容量对比
  • ¥15 winform的chart曲线生成时有凸起
  • ¥15 msix packaging tool打包问题
  • ¥15 finalshell节点的搭建代码和那个端口代码教程
  • ¥15 Centos / PETSc / PETGEM
  • ¥15 centos7.9 IPv6端口telnet和端口监控问题
  • ¥20 完全没有学习过GAN,看了CSDN的一篇文章,里面有代码但是完全不知道如何操作
  • ¥15 使用ue5插件narrative时如何切换关卡也保存叙事任务记录
  • ¥20 海浪数据 南海地区海况数据,波浪数据
  • ¥20 软件测试决策法疑问求解答