2012-10-19 68 views
2

鉴于冗余,是否有更好的方法来做到这一点?如果是这样,它会是什么样子?传递可变参数列表

请注意第一个$method参数,该参数作为函数名称在$api类中传递,并且不能作为参数传递给API函数。其后每一个论证都可能不存在。

function jsonRequest($method) 
{ 
    $api = new JsonRpcClient('https://api.example.com'); 
    switch (func_num_args()) { 
     case 2: 
      $result = $api->$method('AccountRef', 'APIKey', func_get_arg(1)); 
     break; case 3: 
      $result = $api->$method('AccountRef', 'APIKey', func_get_arg(1), func_get_arg(2)); 
     break; case 4: 
      $result = $api->$method('AccountRef', 'APIKey', func_get_arg(1), func_get_arg(2), func_get_arg(3)); 
     break; case 5: 
      $result = $api->$method('AccountRef', 'APIKey', func_get_arg(1), func_get_arg(2), func_get_arg(3), func_get_arg(4)); 
     break; 
    } 
    return json_decode($result); 
} 
+0

你可以使用一个for循环? – twodayslate

+0

那将是什么样子?我考虑过它,但是无法将我的头部用于将函数调用引发的语法。 –

+0

你可以为扩展参数传递'func_get_arg(2)'或'NULL'吗? –

回答

3

你应该使用call_user_func_array

$data = array_merge(array('AccountRef', 'APIKey'), func_get_args()); 

call_user_func_array(array($api, $method), $data); 

来源:http://php.net/manual/en/function.call-user-func-array.php

+0

太棒了,我完全忽略了那个函数认为它是不相关的。 D'哦!只需要现在从该数组中删除$方法。 –

+0

@AndrewBestic - 不要忘了标记它作为答案,如果它的作品。您可以通过单击问题右侧的勾选标记来完成此操作(请注意,每个问题只能接受一个答案)。 –

+0

能够删除初始参数:'$ args = func_get_args(); unset($ args [0]);' –