远期不确定数量的参数给另一个函数 [英] Forward undefined number of arguments to another function

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

问题描述

我会解释这个问题有一个简单的函数接受任何数目的功能

 功能ABC(){
   的$ args = func_get_args();
   //现在让我们使用的第一个参数的东西......在这种情况下,一个简单的回声
   回声的$ args [0];
   //让我们删除此第一个参数
   未设置(的$ args [0]);   //现在我想将剩余的参数发送到不同的功能,以同样的方式,因为它接收
   ..。 ......但不知道如何。 ..................   //试着做这样的事情,对周围的工作
   $ newargs =破灭(,$参数);
   //调用另一个函数
   anotherFUnction($ newargs);然而//这个函数是一个类的构造函数
   // ^这会被视为一个参数,而不是复式参数....}

我希望这个问题是清楚了吧,有什么工作都是围绕这种情况?

更新

我忘了提,我打电话下一个函数是一个构造类另一个类的。
类似

  $ =的NewClass新类($ newarguments);


解决方案

进行简单的函数调用

使用 call_user_func_array ,但不破灭的指定参数时,只剩余args来数组传递给 call_user_func_array

  call_user_func_array('anotherFunction',$参数);


创建对象

使用: ReflectionClass :: newInstanceArgs

  $ refClass =新ReflectionClass('yourClassName');
$ OBJ = $ refClass-> newInstanceArgs($ yourConstructorArgs);

或: ReflectionClass ::的newInstance

  $ refClass =新ReflectionClass('yourClassName');
$ OBJ = call_user_func_array(阵列($ refClass的newInstance'),$ yourConstructorArgs);

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?

Update

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

$newclass = new class($newarguments);

解决方案

for simple function calls

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);


for object creation

use: ReflectionClass::newInstanceArgs

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

or: ReflectionClass::newinstance

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

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

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