你能做点像这样的事吗
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)
答案 0 :(得分:4)
实际上,这很简单(并阅读手册:func_get_args
- 返回一个包含函数参数列表的数组,请参阅:Variable-length argument lists):
function cool_function($pizza, $ice_cream) {
return func_get_args();
}
但正如评论中所说,你为什么需要这个?
或者你需要变量名吗? Reflection Docs是你的朋友:
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());
或两者兼而有之? (编辑:考虑欠长度,可选和超长参数):
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'));
答案 1 :(得分:3)
我不确定你是否在寻找func_get_args
返回传递给函数或ReflectionFunction
类的所有参数。
func_get_args的基本示例:
function cool_function($pizza, $ice_cream) {
return func_get_args();
}
但是你不需要参数来使这项工作:
function cool_function() {
return func_get_args();
}
// cool_function(1,2,3) will return array(1,2,3)
反射选项:
/**
* Returns an array of the names of this function
*/
function getMyArgNames($a,$b,$c)
{
$args = array();
$refFunc = new ReflectionFunction(__FUNCTION__);
foreach( $refFunc->getParameters() as $param ){
$args[] = $param->name;
}
return $args;
}
或者,真的很疯狂:
/**
* Returns an associative array of the names of this function mapped
* to their values
*/
function getMyArgNames($a,$b,$c)
{
$received = func_get_args();
$i = 0;
$args = array();
$refFunc = new ReflectionFunction(__FUNCTION__);
foreach( $refFunc->getParameters() as $param ){
$args[$param->name] = $received[$i++];
}
// include all of those random, optional arguments.
while($i < count($received)) $args[] = $received[$i++];
return $args;
}
答案 2 :(得分:0)
function valuesToArray($value1,$value2){return array($value1,$value2);}
答案 3 :(得分:0)
如果我找对你,你就是这样:
function cool_function($pizza, $ice_cream) {
return array($pizza, $ice_cream);
}
但你可以这样做:
$new_var = array($pizza, $ice_cream);