将未定义数量的参数转发给另一个函数 [英] Forward undefined number of arguments to another function

查看:24
本文介绍了将未定义数量的参数转发给另一个函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我将用一个接受任意数量函数的简单函数来解释这个问题

I will explain the question with a simple function accepting any number of function

function abc() {
   $args = func_get_args();
   //Now lets use the first parameter in something...... In this case a simple echo
   echo $args[0];
   //Lets remove this first parameter 
   unset($args[0]); 

   //Now I want to send the remaining arguments to different function, in the same way as it received
   .. . ...... BUT NO IDEA HOW TO . ..................

   //tried doing something like this, for a work around
   $newargs = implode(",", $args); 
   //Call Another Function
   anotherFUnction($newargs); //This function is however a constructor function of a class
   // ^ This is regarded as one arguments, not mutliple arguments....

}

我希望问题现在已经清楚了,针对这种情况有什么解决办法?

I hope the question is clear now, what is the work around for this situation?

我忘了提到我调用的下一个函数是另一个类的构造函数类.类似的东西

I forgot to mention that the next function I am calling is a constructor class of another class. Something like

$newclass = new class($newarguments);

推荐答案

用于简单的函数调用

使用call_user_func_array,但不要内爆 args,只需将剩余的 args 数组传递给 call_user_func_array

use call_user_func_array, but do not implode the args, just pass the array of remaining args to call_user_func_array

call_user_func_array('anotherFunction', $args);

<小时>

用于创建对象

使用:ReflectionClass::newInstanceArgs

$refClass = new ReflectionClass('yourClassName');
$obj = $refClass->newInstanceArgs($yourConstructorArgs);

或:ReflectionClass::newinstance

$refClass = new ReflectionClass('yourClassName');
$obj = call_user_func_array(array($refClass, 'newInstance'), $yourConstructorArgs);

这篇关于将未定义数量的参数转发给另一个函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆