PHP函数参数到一个数组 [英] PHP Function Argument to an array
本文介绍了PHP函数参数到一个数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
您可以像这样疯狂的事。
函数cool_function($比萨饼,$ ice_cream){ 使阵列中的参数成阵列
返回$ array_of_paramaters //我的新阵} //函数结束的print_r(cool_function); //输出数组(0 =>比萨饼,1 =>冰淇淋)
解决方案
其实,这是pretty容易的(和阅读手册:的 func_get_args
- 返回一个包含函数的参数列表数组,看得那么清楚:的可变长度参数列表中):
函数cool_function($比萨饼,$ ice_cream){
返回func_get_args();
}
但问的意见,你为什么需要这个?
或你需要的变量名? 反射的文件的 是你的朋友:
函数cool_named($中子,电子$)
{
$ F =新ReflectionFunction(__ FUNCTION__);
$ P =阵列();
的foreach($ F-> getParameters()为$ P1)
$ P [] ='$'$ P1-方式>名称; 返回$ P;
}的var_dump(cool_named());
或只是两者兼而有之? (编辑:的考虑下长,可选的超长参数的考虑):
功能全面($中子,电子$,$夸克='xiaro')
{
$ F =新ReflectionFunction(__ FUNCTION__);
$定义= $ F-> getParameters();
$传递= func_get_args()+ array_fill(0,计数($定义),NULL); 的foreach($定义为安培; $参数)
$参数=$$参方式>名称; 返回array_combine($定义+ array_keys($通过),$通过);
}后续代码var_dump(整体('克拉拉','彼得','月亮','木星'));
Can you do something crazy like this
function cool_function($pizza, $ice_cream) {
make the arguments in the array into an array
return $array_of_paramaters // my new array
} // end function
print_r(cool_function); // outputs array(0 => pizza, 1=> ice cream)
解决方案
Actually, this is pretty easy (and read the manual: func_get_args
— Returns an array containing a function's argument list, see as well: Variable-length argument lists):
function cool_function($pizza, $ice_cream) {
return func_get_args();
}
but as asked in comments, why do you need this?
Or do you need the variable names? Reflection Docs is your friend:
function cool_named($neutron, $electron)
{
$f = new ReflectionFunction(__FUNCTION__);
$p = array();
foreach($f->getParameters() as $p1)
$p[] = '$'.$p1->name;
return $p;
}
var_dump(cool_named());
Or just both? (Edit: taking under-length, optional and over-length parameters into account):
function overall($neutron, $electron, $quark = 'xiaro')
{
$f = new ReflectionFunction(__FUNCTION__);
$defined = $f->getParameters();
$passed = func_get_args() + array_fill(0, count($defined), NULL);
foreach($defined as &$param)
$param = '$'.$param->name;
return array_combine($defined + array_keys($passed), $passed);
}
var_dump(overall('clara', 'peter', 'moon', 'jupiter'));
这篇关于PHP函数参数到一个数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文