【问题标题】:Pass array as individual params to a php function将数组作为单个参数传递给 php 函数
【发布时间】:2014-12-08 19:45:11
【问题描述】:

解决方案

感谢noufalcep,我通过使用得到它的工作

public function __call($method, $params){
    return call_user_func_array(array($this->_rpc, $method), $params);
}

原始问题

我创建了一个包含另一个类jsonrpc 的类,以便在我的项目中使用。

jsonrpc 使用public function __call($method, $params) 来处理任何类型的泛型方法。

我也在课堂上使用相同的方法,但这意味着我必须将 $params 数组转换为单独的变量,以作为参数传递给 jsonrpc 的 __call()

如何将$params 的数组更改为多个参数?

在我的包装类中,我尝试使用 ... 来提供参数,但它似乎只在使用 [] 实例化数组时才有效。

一个简单的解决方案是编辑 jsonrpc 类如何处理它的参数,但我更愿意让它的源保持不变。

我尝试过的(显然每个 __call 都是单独尝试的,而不是同时尝试...)

class Wrap{
    //Could have been great, but doesn't work.
    public function __call($method, $params){
        $params = array_values($params);
        return $this->_rpc->$method(...$params);
    }

    //Horrible, but works
    public function __call($method, $params){
        switch (count($params)) {
            case 0:
                return $this->_rpc->$method();
                break;
            case 1:
                return $this->_rpc->$method($params[0]);
                break;
            case 2:
                return $this->_rpc->$method($params[0], $params[1]);
                break;
            case 3:
                return $this->_rpc->$method($params[0], $params[1], $params[2]);
                break;
            case 4:
                return $this->_rpc->$method($params[0], $params[1], $params[2], $params[3]);
                break;
            default:
                die("Horrible way doesn't have enough cases!");
                break;
        }
    }
}

谢谢。

【问题讨论】:

  • 您在使用... 时遇到什么错误?
  • @PHPWeblineindia 这是一个语法错误:意外的 '.',期待 ')'。 Noulacep 有正确的想法here

标签: php parameters arguments call


【解决方案1】:

使用Call_user_func_array

public function __call($method, $params){
    return call_user_func_array($this->_rpc->$method(),$params)
}

【讨论】:

  • 我不得不使用call_user_func_array(array($this->_rpc, $method), $params);,但它起作用了。
猜你喜欢
  • 1970-01-01
  • 2012-12-07
  • 1970-01-01
  • 1970-01-01
  • 2013-01-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多