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 有赏,i卡绘世画不出
  • ¥15 如何用stata画出文献中常见的安慰剂检验图
  • ¥15 c语言链表结构体数据插入
  • ¥40 使用MATLAB解答线性代数问题
  • ¥15 COCOS的问题COCOS的问题
  • ¥15 FPGA-SRIO初始化失败
  • ¥15 MapReduce实现倒排索引失败
  • ¥15 ZABBIX6.0L连接数据库报错,如何解决?(操作系统-centos)
  • ¥15 找一位技术过硬的游戏pj程序员
  • ¥15 matlab生成电测深三层曲线模型代码